package com.mdhw.system.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdhw.common.base.PageData;
import com.mdhw.common.contants.CacheKeyContants;
import com.mdhw.common.enums.AudiStatusEnum;
import com.mdhw.common.enums.MessageEnum;
import com.mdhw.common.enums.StatusEnum;
import com.mdhw.common.enums.SystemNameEnum;
import com.mdhw.common.jwt.JwtProjectProperties;
import com.mdhw.config.AdminJwtProjectProperties;
import com.mdhw.config.R;
import com.mdhw.order.dao.JiaOrderDao;
import com.mdhw.order.dao.JiaOrderPrizePoolRewardDao;
import com.mdhw.order.entity.DailiGetLevelRewardTime;
import com.mdhw.order.entity.DailiPrizePoolLevel;
import com.mdhw.order.entity.JiaOrder;
import com.mdhw.order.entity.JiaOrderPrizePoolReward;
import com.mdhw.order.vo.JiaOrderVo;
import com.mdhw.order.vo.PrizePoolSetVo;
import com.mdhw.system.dao.SysUserDao;
import com.mdhw.system.dao.SysUserTixianLogDao;
import com.mdhw.system.entity.*;
import com.mdhw.system.service.*;
import com.mdhw.system.vo.*;
import com.mdhw.thirdparty.service.impl.SmsAoZhongService;
import com.mdhw.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Huang
 * @date 2022-03-10
 */

@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    @Autowired
    private JwtProjectProperties properties;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysAccountService sysAccountService;
    @Autowired
    private AdminJwtProjectProperties projectProperties;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysDictDataService sysDictDataService;
    @Autowired
    private SmsAoZhongService smsAoZhongService;
    @Autowired
    private QRCodeService qrCodeService;
    @Autowired
    private WechatAppletService wechatAppletService;

    @Autowired
    private AliYunOssServer aliYunOssServer;
    @Autowired
    private JiaOrderDao jiaOrderDao;

    @Autowired
    private JiaOrderPrizePoolRewardDao jiaOrderPrizePoolRewardDao;
    @Autowired
    private SysUserTixianLogDao sysUserTixianLogDao;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private CaoLiaoService caoLiaoService;



    @Override
    public R<PageData<SysUserVo>> selectListPage(Long pageNo, Long pageSize, String loginName, Long roleId) {
        pageNo = pageNo == null ? 1L:pageNo;
        pageSize = pageSize == null ? 10L:pageSize;
        Page page = new Page(pageNo,pageSize);
        Map<Long,SysRole> sysRoleMap = new HashMap<>();
        Map<Long,Long> sysUserRoleMap = new HashMap<>();
        QueryWrapper<SysUserVo> suQw = new QueryWrapper<>();
        if(org.apache.commons.lang.StringUtils.isNotBlank(loginName)){
            suQw.eq("phone",loginName);
        }
        if(roleId != null){
            LambdaQueryWrapper<SysUserRole> surLqw = new LambdaQueryWrapper<>();
            surLqw.eq(SysUserRole::getRoleId,roleId);
            List<SysUserRole> sysUserRoleList = this.sysUserRoleService.list(surLqw);
            List<Long> userIdList = sysUserRoleList.stream().map(d->d.getUserId()).collect(Collectors.toList());
            userIdList.add(-11L);
            suQw.in("id",userIdList);

            SysRole sysRole = this.sysRoleService.getById(roleId);
            sysRoleMap.put(roleId,sysRole);
            for(SysUserRole sysUserRole:sysUserRoleList){
                sysUserRoleMap.put(sysUserRole.getUserId(),sysUserRole.getRoleId());
            }
        }
        suQw.eq("user_type","1");
        suQw.orderByDesc("id");
        this.sysUserDao.selectDarenListpage(page,suQw);
        PageData pageData = PageData.plusPageToPageData(page);
        List<SysUserVo> dataList = pageData.getData();
        if(roleId == null){
            List<Long> userIdList = dataList.stream().map(d->d.getId()).collect(Collectors.toList());
            userIdList.add(-11L);
            LambdaQueryWrapper<SysUserRole> surLqw = new LambdaQueryWrapper<>();
            surLqw.in(SysUserRole::getUserId,userIdList);
            List<SysUserRole> sysUserRoleList = this.sysUserRoleService.list(surLqw);
            for(SysUserRole sysUserRole:sysUserRoleList){
                sysUserRoleMap.put(sysUserRole.getUserId(),sysUserRole.getRoleId());
            }
            Set<Long> roleIdList = new HashSet<>();
            for(SysUserRole sysUserRole:sysUserRoleList){
                roleIdList.add(sysUserRole.getRoleId());
            }
            roleIdList.add(-11L);
            LambdaQueryWrapper<SysRole> srLqw = new LambdaQueryWrapper<>();
            srLqw.in(SysRole::getId,roleIdList);
            List<SysRole> sysRoleList = this.sysRoleService.list(srLqw);
            sysRoleMap = sysRoleList.stream().collect(Collectors.toMap(SysRole::getId, d -> d, (o, n) -> n));
        }
        for(SysUserVo sysUserVo:dataList){
            Long userVoId = sysUserVo.getId();
            Long userRoleId = sysUserRoleMap.get(userVoId);
            SysRole sysRole = sysRoleMap.get(userRoleId);
            if(sysRole != null){
                sysUserVo.setRoleName(sysRole.getName());
                sysUserVo.setRoleCode(sysRole.getCode());
            }
        }

        return R.success(pageData);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R<String> updateSysUser(SysUserVo sysUserVo) {
        Long sysUserId = sysUserVo.getId();
        Long roleId = sysUserVo.getRoleId();
        LambdaQueryWrapper<SysUserRole> surLqw = new LambdaQueryWrapper<>();


        // 先删除
        surLqw.clear();
        surLqw.eq(SysUserRole::getUserId,sysUserId);
        this.sysUserRoleService.remove(surLqw);

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUserId);
        sysUserRole.setRoleId(roleId);
        this.sysUserRoleService.save(sysUserRole);

        // 是否修改我的选品中供货价
        Boolean isUpdateBusinessGoods = Boolean.FALSE;
        // 是否修改 供应商出售比例
        Boolean isUpdateChannelCsbl = Boolean.FALSE;

        SysUser nativeSysUser = this.getById(sysUserId);

        nativeSysUser.setIsPrizePool(sysUserVo.getIsPrizePool());
        BigDecimal newCsbl = new BigDecimal(100);
        BigDecimal nativeCsbl = new BigDecimal(100);

        // 修改 sys_account
        LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
        saLqw.eq(SysAccount::getUserId,sysUserId);
        saLqw.eq(SysAccount::getStatus,StatusEnum.OK.getCode());
        List<SysAccount> sysAccountList = this.sysAccountService.list(saLqw);
        if(sysAccountList != null && sysAccountList.size() > 0){
            SysAccount sysAccount = sysAccountList.get(0);


            BigDecimal newCsBl = sysUserVo.getCsBl() == null ? new BigDecimal(100):sysUserVo.getCsBl();





            newCsbl = newCsBl;

            // 是否是渠道商
            boolean isBusiness = isBusiness(sysUserId);
            if(isBusiness){
                if(nativeCsbl.compareTo(newCsbl) != 0){
                    isUpdateBusinessGoods = Boolean.TRUE;
                }
            }
            // 是否是供应商
            Boolean isChannel = isChannel(sysUserId);
            if(isChannel){
                if(nativeCsbl.compareTo(newCsbl) != 0){
                    isUpdateChannelCsbl = Boolean.TRUE;
                }
            }
            this.sysAccountService.updateById(sysAccount);
        }


//        BeanUtils.copyProperties(sysUserVo, nativeSysUser);
        nativeSysUser.setLoginName(sysUserVo.getLoginName());
        nativeSysUser.setPhone(sysUserVo.getPhone());
        nativeSysUser.setHeaderUrl(sysUserVo.getHeaderUrl());
        nativeSysUser.setLoginName(sysUserVo.getLoginName());
        //nativeSysUser.setEmail(sysUserVo.getEmail());
        if(StringUtils.hasText(sysUserVo.getUserType())){
            nativeSysUser.setUserType(sysUserVo.getUserType());
        }

        //String encryptPassword = EncryptUtil.encrypt(sysUserVo.getPassword(), nativeSysUser.getSalt());
        // nativeSysUser.setPassword(encryptPassword);
        boolean isSuccess = this.updateById(nativeSysUser);
        if(isSuccess){
            return R.success("修改成功");
        }else{
            return R.error("修改失败");
        }
    }

    @Override
    public R<String> login(SysUser sysUser) {
        String loginName = sysUser.getLoginName();
        String password = sysUser.getPassword();
        String salt = sysUser.getSalt();
        // 明文密码加密处理
        String encrypt = EncryptUtil.encrypt(password, salt);

        return null;
    }

    /**
     * 验证密码登录
     * @param sysUser
     * @return
     */
    @Override
    public R<SysUserVo> authPwd(SysUserVo sysUser) {
        String loginName = sysUser.getLoginName();
        String password = sysUser.getPassword();
        Date nowTime = new Date();
        LambdaQueryWrapper<SysUser> sysUserLqw = new LambdaQueryWrapper<>();
        sysUserLqw.eq(SysUser::getPhone,loginName);
        sysUserLqw.eq(SysUser::getStatus, StatusEnum.OK.getCode().toString());
        List<SysUser> sysUserList = this.list(sysUserLqw);
        if(sysUserList == null || sysUserList.size() == 0){
            return R.error(MessageEnum.NO_ACCOUNT.getMessage().toString());
        }
        SysUser nativeSysUser = sysUserList.get(0);
        String salt =nativeSysUser.getSalt();
        // 对明文密码加密处理
        String encrypt = EncryptUtil.encrypt(password, salt);
        String nativePassword = nativeSysUser.getPassword();
        SysUserVo sysUserVo = new SysUserVo();
        // 判断密码是否正确
        if(encrypt.equals(nativePassword)){
            String token = JwtUtil.getToken("Bearer", nativeSysUser.getId(), properties.getSecret(), properties.getExpired());
            BeanUtils.copyProperties(nativeSysUser,sysUserVo);
            sysUserVo.setToken(token);
            if(nativeSysUser.getIsOpen() == null || "0".equals(nativeSysUser.getIsOpen())){
                return R.error(MessageEnum.AUTH_STOP_ERROR.getMessage());
            }
            Long sysUserId = nativeSysUser.getId();
            // 用户角色
            List<SysRoleVo> sysRoleVoList = this.sysUserDao.selectRoleListByUser(sysUserId);
            // 用户菜单
            List<SysMenuVo> sysMenuVoList = this.sysUserDao.selectMenuListByUser(sysUserId);
            // 用户接口权限
            List<String> permissionList = new ArrayList<>();
            for(SysMenuVo sysMenuVo:sysMenuVoList){
                permissionList.add(sysMenuVo.getApiUrl());
            }
            String requestIp = IpAddressUtil.getRequestIp();
            //nativeSysUser.setLastLoginIp(requestIp);
            //最后登录时间
            //nativeSysUser.setLastLoginTime(new Date());
            boolean isSuccess = this.updateById(nativeSysUser);
            if(isSuccess){
                LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
                saLqw.eq(SysAccount::getUserId,sysUserId);
                saLqw.eq(SysAccount::getStatus,StatusEnum.OK.getCode());
                SysAccount sysAccount = this.sysAccountService.getOne(saLqw, Boolean.FALSE);
                if(sysAccount != null){
                    sysAccount.setLastLoginTime(nowTime);
                    sysAccount.setLastLoginIp(requestIp);
                    this.sysAccountService.updateById(sysAccount);
                }
            }


            sysUserVo.setPassword(null);
            sysUserVo.setSalt(null);
            sysUserVo.setLastLoginIp(null);
            redisUtil.set(CacheKeyContants.MILI_USER_ROLE+sysUserId,sysRoleVoList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_MENU+sysUserId,sysMenuVoList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_PERMISSION+sysUserId,permissionList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_TOKEN+sysUserId,token, projectProperties.getExpired());
            return R.success("登录成功",sysUserVo);
        }else {
            return R.error(MessageEnum.AUTH_REQUEST_ERROR.getMessage().toString());
        }
    }


    @Override
    public R<SysUserVo> authPwdByCode(SysUser sysUser) {
        String loginName = sysUser.getPhone();
        String password = sysUser.getPassword();
        Date nowTime = new Date();
        LambdaQueryWrapper<SysUser> sysUserLqw = new LambdaQueryWrapper<>();
        sysUserLqw.eq(SysUser::getPhone,loginName);
        sysUserLqw.eq(SysUser::getStatus, StatusEnum.OK.getCode().toString());
        List<SysUser> sysUserList = this.list(sysUserLqw);
        if(sysUserList == null || sysUserList.size() == 0){
            return R.error(MessageEnum.NO_ACCOUNT.getMessage().toString());
        }
        SysUser nativeSysUser = sysUserList.get(0);
        String salt =nativeSysUser.getSalt();
        // 对明文密码加密处理
        SysUserVo sysUserVo = new SysUserVo();
        // 判断密码是否正确

            String token = JwtUtil.getToken("Bearer", nativeSysUser.getId(), properties.getSecret(), properties.getExpired());
            BeanUtils.copyProperties(nativeSysUser,sysUserVo);
            sysUserVo.setToken(token);
            if(nativeSysUser.getIsOpen() == null || "0".equals(nativeSysUser.getIsOpen())){
                return R.error(MessageEnum.AUTH_STOP_ERROR.getMessage());
            }
            Long sysUserId = nativeSysUser.getId();
            // 用户角色
            List<SysRoleVo> sysRoleVoList = this.sysUserDao.selectRoleListByUser(sysUserId);
            // 用户菜单
            List<SysMenuVo> sysMenuVoList = this.sysUserDao.selectMenuListByUser(sysUserId);
            // 用户接口权限
            List<String> permissionList = new ArrayList<>();
            for(SysMenuVo sysMenuVo:sysMenuVoList){
                permissionList.add(sysMenuVo.getApiUrl());
            }
            String requestIp = IpAddressUtil.getRequestIp();
            //nativeSysUser.setLastLoginIp(requestIp);
            //最后登录时间
            //nativeSysUser.setLastLoginTime(new Date());
            boolean isSuccess = this.updateById(nativeSysUser);
            if(isSuccess){
                LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
                saLqw.eq(SysAccount::getUserId,sysUserId);
                saLqw.eq(SysAccount::getStatus,StatusEnum.OK.getCode());
                SysAccount sysAccount = this.sysAccountService.getOne(saLqw, Boolean.FALSE);
                if(sysAccount != null){
                    sysAccount.setLastLoginTime(nowTime);
                    sysAccount.setLastLoginIp(requestIp);
                    this.sysAccountService.updateById(sysAccount);
                }
            }


            sysUserVo.setPassword(null);
            sysUserVo.setSalt(null);
            sysUserVo.setLastLoginIp(null);
            redisUtil.set(CacheKeyContants.MILI_USER_ROLE+sysUserId,sysRoleVoList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_MENU+sysUserId,sysMenuVoList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_PERMISSION+sysUserId,permissionList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_TOKEN+sysUserId,token, projectProperties.getExpired());
            return R.success("登录成功",sysUserVo);

    }

    @Override
    public R<SysUserVo> authPwdHoutai(SysUser sysUser) {
        Date nowTime = new Date();
        String requestIp = IpAddressUtil.getRequestIp();
        String phone = sysUser.getPhone();
        String password = sysUser.getPassword();
        SysLog sysLog = new SysLog();
        sysLog.setSystemName("系统操作人员");
        sysLog.setModuleName("成员模块");
        sysLog.setModuleValue("后台登录");
        sysLog.setMethodName("com.mdhw.system.controller.SysUserController.loginHoutai()");
        JSONObject paramsJson = new JSONObject();
        paramsJson.put("phone",phone);
        paramsJson.put("password",password);
        sysLog.setParams(paramsJson.toJSONString());
        sysLog.setIp(requestIp);
        sysLog.setStatus(StatusEnum.OK.getCode());
        sysLog.setCreateUser(phone);
        sysLog.setCreateDate(nowTime);

        LambdaQueryWrapper<SysUser> sysUserLqw = new LambdaQueryWrapper<>();
        sysUserLqw.eq(SysUser::getPhone,phone);
        sysUserLqw.eq(SysUser::getStatus, StatusEnum.OK.getCode().toString());
        List<SysUser> sysUserList = this.list(sysUserLqw);
        if(sysUserList == null || sysUserList.size() == 0){
            sysLog.setResponse(MessageEnum.NO_ACCOUNT.getMessage().toString());
            this.sysLogService.save(sysLog);
            return R.error(MessageEnum.NO_ACCOUNT.getMessage().toString());
        }
        SysUser nativeSysUser = sysUserList.get(0);
        if(org.apache.commons.lang.StringUtils.isBlank(nativeSysUser.getUserType()) || !"1".equals(nativeSysUser.getUserType())){
            sysLog.setResponse("您并非后台用户，暂时无法登录，请联系管理员");
            this.sysLogService.save(sysLog);
            return R.error("您并非后台用户，暂时无法登录，请联系管理员");
        }
        String salt =nativeSysUser.getSalt();
        // 对明文密码加密处理
        String encrypt = EncryptUtil.encrypt(password, salt);
        String nativePassword = nativeSysUser.getPassword();
        SysUserVo sysUserVo = new SysUserVo();
        // 判断密码是否正确
        if(encrypt.equals(nativePassword)){
            Long sysUserId = nativeSysUser.getId();
            // 用户角色
            List<SysRoleVo> sysRoleVoList = this.sysUserDao.selectRoleListByUser(sysUserId);
            // 用户菜单
            List<SysMenuVo> sysMenuVoList = this.sysUserDao.selectMenuListByUser(sysUserId);
            // 用户接口权限
            List<String> permissionList = new ArrayList<>();
            for(SysMenuVo sysMenuVo:sysMenuVoList){
                permissionList.add(sysMenuVo.getApiUrl());
            }
            // 如果有 token 了，就直接用原来的token
            Object oldTokenObj = this.redisUtil.get(CacheKeyContants.MILI_USER_TOKEN + sysUserId);
            if(oldTokenObj != null){
                String oldTokenStr = (String) oldTokenObj;
                BeanUtils.copyProperties(nativeSysUser,sysUserVo);
                sysUserVo.setToken(oldTokenStr);
                redisUtil.set(CacheKeyContants.MILI_USER_ROLE+sysUserId,sysRoleVoList, projectProperties.getExpired());
                redisUtil.set(CacheKeyContants.MILI_USER_MENU+sysUserId,sysMenuVoList, projectProperties.getExpired());
                redisUtil.set(CacheKeyContants.MILI_USER_PERMISSION+sysUserId,permissionList, projectProperties.getExpired());
                sysLog.setResponse("登录成功");
                this.sysLogService.save(sysLog);
                return R.success(sysUserVo);
            }
            String token = JwtUtil.getToken("Bearer", nativeSysUser.getId(), properties.getSecret(), properties.getExpired());
            BeanUtils.copyProperties(nativeSysUser,sysUserVo);
            sysUserVo.setToken(token);
            if(nativeSysUser.getIsOpen() == null || "0".equals(nativeSysUser.getIsOpen())){
                sysLog.setResponse(MessageEnum.AUTH_STOP_ERROR.getMessage());
                this.sysLogService.save(sysLog);
                return R.error(MessageEnum.AUTH_STOP_ERROR.getMessage());
            }




            //nativeSysUser.setLastLoginIp(requestIp);
            //最后登录时间
            //nativeSysUser.setLastLoginTime(new Date());
            this.updateById(nativeSysUser);
            sysUserVo.setPassword(null);
            sysUserVo.setSalt(null);
            sysUserVo.setLastLoginIp(null);
            redisUtil.set(CacheKeyContants.MILI_USER_ROLE+sysUserId,sysRoleVoList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_MENU+sysUserId,sysMenuVoList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_PERMISSION+sysUserId,permissionList, projectProperties.getExpired());
            redisUtil.set(CacheKeyContants.MILI_USER_TOKEN+sysUserId,token, projectProperties.getExpired());

            // 保存登录日志

            sysLog.setResponse("登录成功");
            this.sysLogService.save(sysLog);
            return R.success("登录成功",sysUserVo);
        }else {
            sysLog.setResponse(MessageEnum.AUTH_REQUEST_ERROR.getMessage().toString());
            this.sysLogService.save(sysLog);
            return R.error(MessageEnum.AUTH_REQUEST_ERROR.getMessage().toString());
        }
    }


    @Override
    public SysUserVo getUserVoByToken(){
        String token = JwtUtil.getRequestToken(request);
        String userId = JwtUtil.parseToken(token);
//        String userId = WebContextUtil.getUserToken();
        if (userId == null) {
            return null;
        }
        SysUser sysUser = this.getById(userId);
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(sysUser,sysUserVo);
        return sysUserVo;
    }


    /**
     * 系统用户新增
     * @param sysUserVo
     * @return
     */
    @Override
    public R<String> addSysUser(SysUserVo sysUserVo) {
        SysUserVo currentSysUserVo = this.selectUserByToken();
        if(sysUserVo == null){
            return R.error("未登录，无权限！");
        }
        if(!currentSysUserVo.getIsAdmin()){
            return R.error("非管理员，无权限！");
        }
        if(!"1".equals(currentSysUserVo.getUserType())){
            return R.error("非系统人员，无权限！");
        }

        Long roleId1 = sysUserVo.getRoleId();
        SysRole role = this.sysRoleService.getById(roleId1);
        if(role == null){
            return R.error("新增失败，无角色");
        }
        Date nowTime = new Date();

        SysUser sysUser = new SysUser();
        sysUser.setCreateDate(nowTime);
        sysUser.setUpdateDate(nowTime);
        sysUser.setRevision(0);
        sysUser.setStatus(StatusEnum.OK.getCode().toString());
        sysUser.setSortNum(0);
        //生成盐值
        String salt = EncryptUtil.getRandomSalt();
        String pwd = EncryptUtil.encrypt(sysUserVo.getPassword(), salt);
        sysUser.setPassword(pwd);
        sysUser.setSalt(salt);
        sysUser.setLoginName(sysUserVo.getLoginName());
        sysUser.setPhone(sysUserVo.getLoginName());
        //sysUser.setEmail(sysUserVo.getEmail());
        sysUser.setName(sysUserVo.getName());

        sysUser.setUserType("1");

        sysUser.setIsOpen("1");
        sysUser.setIsPrizePool("1");


        String baseStr = "0123456789";

        LambdaQueryWrapper<SysUser> suLqw2 = new LambdaQueryWrapper<>();
        suLqw2.select(SysUser::getYaoqingma);
        suLqw2.isNotNull(SysUser::getYaoqingma);
        List<SysUser> nativeYaoqingmUserList = this.list(suLqw2);
        Set<String> oldYaoqingmaSet = new HashSet<>();
        for(SysUser sysUser1:nativeYaoqingmUserList){
            oldYaoqingmaSet.add(sysUser1.getYaoqingma());
        }
        String newYaoqingma = RandomUtil.randomString(baseStr, 6);

        while (!oldYaoqingmaSet.add(newYaoqingma)){
            newYaoqingma = RandomUtil.randomString(baseStr, 6);
        }
        sysUser.setYaoqingma(newYaoqingma);
        String qrCode = this.wechatAppletService.getUnlimitedQRCode("wx7bd68c82356a3f87", "258684f2a8faa47e1ce55969a1916df0", "pages/index/register", newYaoqingma);
        sysUser.setQrCode(qrCode);
        sysUser.setBalance(BigDecimal.ZERO);
        sysUser.setIsZhizhun("0");
        sysUser.setParentZhizhunUserId(0L);
        sysUser.setIsFective("0");
        sysUser.setZhituirenshu(0);
        sysUser.setCanTixian(BigDecimal.ZERO);

        Long pid = -11L;
        String yaoqingma = sysUserVo.getYaoqingma();
        if(org.apache.commons.lang.StringUtils.isNotBlank(yaoqingma)){
            LambdaQueryWrapper<SysUser> yaoUserLqw = new LambdaQueryWrapper<>();
            yaoUserLqw.eq(SysUser::getYaoqingma,yaoqingma);
            yaoUserLqw.eq(SysUser::getStatus,StatusEnum.OK.getCode());
            SysUser yaoqingUser = this.getOne(yaoUserLqw, Boolean.FALSE);
            if(yaoqingUser != null){
                pid = yaoqingUser.getId();
                sysUser.setPid(pid);
            }
        }
        boolean isSuccess = this.save(sysUser);
        Long userId = sysUser.getId();

        LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
        saLqw.eq(SysAccount::getUserId,pid);
        saLqw.eq(SysAccount::getStatus,StatusEnum.OK.getCode());
        SysAccount pSysAccount = this.sysAccountService.getOne(saLqw, Boolean.FALSE);


        SysAccount sysAccount = new SysAccount();
        sysAccount.setRevision(0);
        sysAccount.setStatus(StatusEnum.OK.getCode());
        sysAccount.setCreateDate(nowTime);
        sysAccount.setUpdateDate(nowTime);
        sysAccount.setUserId(userId);
        String xianStr = "";
        if (pSysAccount != null){
            xianStr = pSysAccount.getXianStr();
            xianStr = xianStr + userId+",";
        }else{
            xianStr = ","+userId+",";
        }
        sysAccount.setXianStr(xianStr);

        this.sysAccountService.save(sysAccount);

        Long roleId = sysUserVo.getRoleId();

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userId);
        sysUserRole.setRoleId(roleId);
        this.sysUserRoleService.save(sysUserRole);
        if(isSuccess){
            return R.success("新增成功");
        }else{
            return R.error("新增失败");
        }
    }



    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R<String> addSysUserRole(SysUserVo sysUserVo) {
        SysUserVo sysUser = this.getUserVoByToken();
        // 先删除再新增
        LambdaQueryWrapper<SysUserRole> surLqw = new LambdaQueryWrapper<>();
        surLqw.eq(SysUserRole::getUserId,sysUserVo.getId());
        this.sysUserRoleService.remove(surLqw);

        Date nowTime = new Date();
        String loginName = sysUser.getLoginName();
        List<Long> roleIdList = sysUserVo.getRoleIdList();
        List<SysUserRole> sysUserRoleList = new ArrayList<>();
        for(Long roleId:roleIdList){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUserVo.getId());
            sysUserRole.setRoleId(roleId);
            sysUserRole.setCreateUser(loginName);
            sysUserRole.setCreateDate(nowTime);
            sysUserRoleList.add(sysUserRole);
        }
        boolean isSuccess = this.sysUserRoleService.saveBatch(sysUserRoleList);

        if(isSuccess){
            return R.success("新增成功");
        }else{
            return R.error("新增失败");
        }
    }

    /**
     * 系统用户修改
     * @param sysUser
     * @return
     */
    public R<String> updateSysUser(SysUser sysUser) {
        Date nowTime = new Date();
        SysUserVo sysUserVo = this.getUserVoByToken();
        String loginName = sysUserVo.getLoginName();
        LambdaQueryWrapper<SysUser> sysUserLqw = new LambdaQueryWrapper<>();
        sysUserLqw.eq(SysUser::getStatus,StatusEnum.OK.getCode().toString());
        sysUserLqw.eq(SysUser::getLoginName,loginName);
        sysUserLqw.eq(SysUser::getUserType,sysUser.getUserType());
        sysUserLqw.ne(SysUser::getId,sysUser.getId());
        List<SysUser> sysUserList = this.list(sysUserLqw);
        if(sysUserList != null && sysUserList.size() > 0){
            return R.error("登录名请勿重复!");
        }else{
            sysUser.setUpdateUser(loginName);
            sysUser.setUpdateDate(nowTime);
            boolean isSuccess = this.updateById(sysUser);
            if(isSuccess){
                return R.success("修改成功");
            }else{
                return R.error("修改失败");
            }
        }
    }

    /**
     * 系统用户删除
     * @param id 用户ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R<String> deleteSysUser(Long id) {
        LambdaQueryWrapper<SysUserRole> surLqw = new LambdaQueryWrapper<>();
        surLqw.eq(SysUserRole::getUserId,id);
        this.sysUserRoleService.remove(surLqw);

        LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
        saLqw.eq(SysAccount::getUserId,id);
        List<SysAccount> sysAccountList = this.sysAccountService.list(saLqw);
        if(sysAccountList != null && sysAccountList.size() > 0){
            SysAccount sysAccount = sysAccountList.get(0);
            sysAccount.setStatus(StatusEnum.DELETE.getCode());
            this.sysAccountService.updateById(sysAccount);
        }

        Date nowTime = new Date();
        SysUserVo sysUserVo = this.getUserVoByToken();
        SysUser sysUser = this.getById(id);
        sysUser.setUpdateDate(nowTime);
        sysUser.setUpdateUser(sysUserVo.getLoginName());
        sysUser.setStatus(StatusEnum.DELETE.getCode().toString());
        boolean isSuccess = this.updateById(sysUser);
        if(isSuccess){
            return R.success("删除成功");
        }else{
            return R.error("删除失败");
        }
    }

    /**
     * 获取当前用户详细信息，菜单，角色，
     * @param id
     * @return
     */
    @Override
    public R<SysUserVo> getUserInfo(Long id) {
        SysUserVo sysUserVo = new SysUserVo();
        SysUser sysUser = this.getById(id);

        return null;
    }

    /**
     * 是否 Admin
     * @param id
     * @return
     */
    @Override
    public boolean isSystemAdmin(Long id) {
        List<SysRoleVo> sysRoleVoList = (List<SysRoleVo>) redisUtil.get(CacheKeyContants.MILI_USER_ROLE+id);
        if (!CollectionUtils.isEmpty(sysRoleVoList)) {
            if (sysRoleVoList.stream().anyMatch(r -> "admin".equals(r.getCode()))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是平台
     * @param id
     * @return
     */
    @Override
    public boolean isPlatform(Long id) {
        List<SysRoleVo> sysRoleVoList = (List<SysRoleVo>) redisUtil.get(CacheKeyContants.MILI_USER_ROLE+id);
        if (!CollectionUtils.isEmpty(sysRoleVoList)) {
            if (sysRoleVoList.stream().anyMatch(r -> "platform".equals(r.getCode()))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否供应商
     * @param id
     * @return
     */
    @Override
    public boolean isChannel(Long id) {
        List<SysRoleVo> sysRoleVoList = (List<SysRoleVo>) redisUtil.get(CacheKeyContants.MILI_USER_ROLE+id);
        if (!CollectionUtils.isEmpty(sysRoleVoList)) {
            if (sysRoleVoList.stream().anyMatch(r -> "channel".equals(r.getCode()))) {
                return true;
            }
        }else{
            // 用户角色
            sysRoleVoList = this.sysUserDao.selectRoleListByUser(id);
            if (!CollectionUtils.isEmpty(sysRoleVoList)) {
                if (sysRoleVoList.stream().anyMatch(r -> "channel".equals(r.getCode()))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 是否渠道商
     * @param id
     * @return
     */
    public boolean isBusiness(Long id){
        List<SysRoleVo> sysRoleVoList = (List<SysRoleVo>) redisUtil.get(CacheKeyContants.MILI_USER_ROLE+id);
        if (!CollectionUtils.isEmpty(sysRoleVoList)) {
            if (sysRoleVoList.stream().anyMatch(r -> "business".equals(r.getCode()))) {
                return true;
            }
        }
        return false;
    }


    @Override
    public SysUserVo selectUserByToken() {
//        String userIdStr = WebContextUtil.getUserToken();
        String token = JwtUtil.getRequestToken(request);
        String userIdStr = JwtUtil.parseToken(token);
        if (userIdStr == null) {
            return null;
        }
        Long userId = Long.parseLong(userIdStr);
        SysUser sysUser = this.getById(userId);
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(sysUser,sysUserVo);
        List<SysMenuVo> sysMenuVoList = this.sysUserDao.selectMenuListByUser(userId);
        List<SysMenuVo> sysMenuVoList2 = new ArrayList<>();
        for(SysMenuVo sysMenuVo:sysMenuVoList){
            String type = sysMenuVo.getType();
            Long parentId = sysMenuVo.getParentId();
            String status = sysMenuVo.getStatus();
            if("155".equals(parentId.toString())){
                continue;
            }
            if("32".equals(parentId.toString())){
                continue;
            }
            if("2".equals(type)) {
                sysMenuVoList2.add(sysMenuVo);
            }
        }

        List<SysRoleVo> sysRoleVoList = this.sysUserDao.selectRoleListByUser(userId);

        boolean isAdmin = this.isSystemAdmin(userId);

        if(isAdmin){
            LambdaQueryWrapper<SysMenu> smLqw = new LambdaQueryWrapper<>();
            smLqw.eq(SysMenu::getStatus,StatusEnum.OK.getCode());
            List<SysMenu> sysMenuList = this.sysMenuService.list(smLqw);
            sysMenuVoList = new ArrayList<>();
            for(SysMenu sysMenu:sysMenuList){
                SysMenuVo sysMenuVo = new SysMenuVo();
                BeanUtils.copyProperties(sysMenu,sysMenuVo);
                sysMenuVoList.add(sysMenuVo);
            }
        }

        LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
        //saLqw.eq(SysAccount::getStatus,StatusEnum.OK.getCode());
        saLqw.eq(SysAccount::getUserId,userId);
        saLqw.orderByDesc(SysAccount::getId);
        List<SysAccount> sysAccountList = this.sysAccountService.list(saLqw);
        if(sysAccountList != null && sysAccountList.size() > 0){
            SysAccount sysAccount = sysAccountList.get(0);
            sysUserVo.setJifen(sysAccount.getJifen());
        }

        sysUserVo.setSysMenuVoList(sysMenuVoList);
        sysUserVo.setSysMenuVoList2(sysMenuVoList2);
        sysUserVo.setSysRoleVoList(sysRoleVoList);
        sysUserVo.setIsAdmin(isAdmin);
        BigDecimal totalShouyi = BigDecimal.ZERO;


        sysUserVo.setShouyi(totalShouyi);
        Long levelId = sysUserVo.getLevelId();


        LambdaQueryWrapper<JiaOrder> joLqw = new LambdaQueryWrapper<>();
        joLqw.eq(JiaOrder::getPUserId,userId);
        joLqw.eq(JiaOrder::getStatus,StatusEnum.OK.getCode());
        joLqw.eq(JiaOrder::getIsShangwu,"0");
        joLqw.eq(JiaOrder::getAudiStatus, AudiStatusEnum.ADUI_STATUS_5.getCode());
        joLqw.eq(JiaOrder::getIsLiangfang, "1");
        joLqw.groupBy(JiaOrder::getUserId);
        List<JiaOrder> jiaOrders = jiaOrderDao.selectList(joLqw);
        if(jiaOrders != null){
            sysUserVo.setZhiyingrenshu(jiaOrders.size());
        }
        List<String> gonggao = new ArrayList<>();
        gonggao.add("平台注意事项");
        gonggao.add("1，不要和上门的装修人员谈论平台的任何事情。");
        gonggao.add("2，平台订单以装修公司上门量房并点确认为有效订单。");
        gonggao.add("3，结算以每月15号和30号为准，结算提现金额。");
        gonggao.add("4，提交资料的客户要保证手机畅通，在没接到客服电话之前，保证所有来电接听，避免电话漏接，平台会三小时内电话联系。");
        gonggao.add("5，平台工作时间为早九点到晚五点。如果入单太多，工作顺延。");
        gonggao.add("6，谈好上门时间要守时，不用轻易更改。");
        gonggao.add("7，遇到问题请联系客服。");
        sysUserVo.setGonggao(gonggao);


        String userType = sysUserVo.getUserType();
        if("1".equals(userType)){
            sysUserVo.setIsSystem(Boolean.TRUE);
            LambdaQueryWrapper<SysUserRole> surLqw = new LambdaQueryWrapper<>();
            surLqw.eq(SysUserRole::getUserId,userId);
            SysUserRole sysUserRole = this.sysUserRoleService.getOne(surLqw, Boolean.FALSE);
            if(sysUserRole != null){
                Long roleId = sysUserRole.getRoleId();
                SysRole sysRole = this.sysRoleService.getById(roleId);
                if(sysRole != null){
                    sysUserVo.setRoleName(sysRole.getName());
                    sysUserVo.setRoleCode(sysRole.getCode());
                }
            }
        }else if("2".equals(userType)){
            sysUserVo.setIsSystem(Boolean.FALSE);
        }
        sysUserVo.setAppQrCode(sysUserVo.getQrCode());


        return sysUserVo;
    }

    @Override
    public String findSystemNameByUserId(String userId) {
        List<SysRoleVo> sysRoleVoList = (List<SysRoleVo>) redisUtil.get(CacheKeyContants.MILI_USER_ROLE+userId);
        if (!CollectionUtils.isEmpty(sysRoleVoList)) {
            if (sysRoleVoList.stream().anyMatch(r -> SystemNameEnum.SYSTEM_NAME_BUSINESS.getCode().equals(r.getCode()))) {
                return SystemNameEnum.SYSTEM_NAME_BUSINESS.getMessage();
            }
            if (sysRoleVoList.stream().anyMatch(r -> SystemNameEnum.SYSTEM_NAME_CHANNEL.getCode().equals(r.getCode()))) {
                return SystemNameEnum.SYSTEM_NAME_CHANNEL.getMessage();
            }
            if (sysRoleVoList.stream().anyMatch(r -> SystemNameEnum.SYSTEM_NAME_PLATFORM.getCode().equals(r.getCode()))) {
                return SystemNameEnum.SYSTEM_NAME_PLATFORM.getMessage();
            }
            if (sysRoleVoList.stream().anyMatch(r -> SystemNameEnum.SYSTEM_NAME_ADMIN.getCode().equals(r.getCode()))) {
                return SystemNameEnum.SYSTEM_NAME_ADMIN.getMessage();
            }
        }
        return null;
    }


    /**
     * 查询供应商列表
     * @return
     */
    @Override
    public List<SysUserVo> selectChannelList(String keyWords) {
        List<SysUserVo> sysUserVos = this.sysUserDao.selectUserListByRole(SystemNameEnum.SYSTEM_NAME_CHANNEL.getCode(),keyWords);
        for(SysUserVo sysUserVo:sysUserVos){
            sysUserVo.setSalt(null);
            sysUserVo.setPassword(null);


        }
        return sysUserVos;
    }

    /**
     * 查询渠道商列表
     * @return
     */
    @Override
    public List<SysUserVo> selectBusinessList(String keyWords) {
        List<SysUserVo> sysUserVos = this.sysUserDao.selectUserListByRole(SystemNameEnum.SYSTEM_NAME_BUSINESS.getCode(),keyWords);
        for(SysUserVo sysUserVo:sysUserVos){
            sysUserVo.setSalt(null);
            sysUserVo.setPassword(null);


        }
        return sysUserVos;
    }

    @Override
    public R<PageData<SysUserVo>> listChanneOrBusiness(Long pageNo, Long pageSize, String loginName, String type,String keyWrods) {
        if(!StringUtils.hasText(type)){
            return  R.error("列表类型为空");
        }
        //查询角色信息
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysRole::getStatus, StatusEnum.OK.getCode());
        lqw.eq(SysRole::getCode, type);
        SysRole sysRole = sysRoleService.getOne(lqw);
        pageNo = pageNo == null ? 1L:pageNo;
        pageSize = pageSize == null ? 10L:pageSize;
        Page page = new Page(pageNo,pageSize);
        QueryWrapper<SysUser> suQw = new QueryWrapper<>();
        suQw.eq("su.status",StatusEnum.OK.getCode());
        if(loginName != null){
            suQw.like("su.login_name",loginName);
        }
        if(keyWrods != null){
            suQw.and(wrapper ->wrapper.like("su.login_name","%"+keyWrods+"%")
            .or().like("su.phone","%"+keyWrods+"%"));
        }
        suQw.eq("sur.role_id",sysRole.getId());

        this.sysUserDao.selectUserDetailPage(page, suQw);
        PageData<SysUserVo> pageData = PageData.plusPageToPageData(page);
        return R.success(pageData);
    }

    @Override
    public R<String> resetPassword(SysUserResetVo sysUserResetVo) {
        SysUser sysUser = this.getById(sysUserResetVo.getId());
        if(sysUser == null){
            return  R.error("没有该用户信息");
        }
        //生成盐值
        String salt = EncryptUtil.getRandomSalt();
        String pwd = EncryptUtil.encrypt("erp@ChaoXm##2022.", salt);
        sysUser.setPassword(pwd);
        sysUser.setSalt(salt);
        sysUser.setUpdateDate(new Date());
        this.updateById(sysUser);
        //删除redis
        redisUtil.del(CacheKeyContants.MILI_USER_TOKEN+sysUser.getId());
        return R.success("重置成功");
    }

    /**
     * 获取供应商列表下拉框
     * @param keyWords 关键字
     * @return
     */
    @Override
    public R<List<SysUserVo>> selectChannelNoPermissionList(String keyWords) {



        return null;
    }

    /**
     * 渠道主用户列表
     * @return
     */
    @Override
    public R<PageData<SysUserVo>> selectQudaozhuUserList(Integer pageNo,Integer pageSize,String loginName,String name,String phone) {
        SysUserVo sysUserVo = this.getUserVoByToken();
        if(sysUserVo == null){
            return R.error("未登录，无权限");
        }
        Integer level = sysUserVo.getLevel();
        if(level == 3 || level == 2){
            return R.error("无权限");
        }
        Long currentUserId = sysUserVo.getId();
        String currentName = sysUserVo.getName();
        Boolean isAdmin = sysUserVo.getIsAdmin();
        Page page = new Page(pageNo,pageSize);
        QueryWrapper<SysUserVo> suvQw = new QueryWrapper<>();
        suvQw.eq("user_type","2");
        suvQw.eq("level",2);
        if(level == 1){
            suvQw.eq("pid",currentUserId);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(loginName)){
            suvQw.eq("login_name",loginName);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(name)){
            suvQw.eq("name",name);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(phone)){
            suvQw.eq("phone",phone);
        }
        this.sysUserDao.selectDarenListpage(page,suvQw);
        PageData<SysUserVo> pageData = PageData.plusPageToPageData(page);
        List<SysUserVo> dataList = pageData.getData();
        List<Long> pIdList = new ArrayList<>();
        pIdList.add(-11L);
        if(level == 1){
            for(SysUserVo sysUserVo1:dataList){
                sysUserVo1.setAdminValue(name);
            }
        }else{
            for(SysUserVo sysUserVo1:dataList){
                pIdList.add(sysUserVo1.getPid());
            }
            LambdaQueryWrapper<SysUser> suLqw = new LambdaQueryWrapper<>();
            suLqw.select(SysUser::getId,SysUser::getLoginName);
            suLqw.eq(SysUser::getUserType,"2");
            suLqw.eq(SysUser::getPid,0);
            suLqw.eq(SysUser::getLevel,1);
            List<SysUser> level1SysUserList = this.list(suLqw);
            Map<Long, SysUser> level1SysUserMap = level1SysUserList.stream().collect(Collectors.toMap(SysUser::getId, d -> d, (o, n) -> n));
            for(SysUserVo sysUserVo1:dataList){
                Long pid = sysUserVo1.getPid();
                SysUser pSysUser = level1SysUserMap.get(pid);
                if(pSysUser == null){
                    continue;

                }
                String pName = pSysUser.getLoginName();
                sysUserVo1.setAdminValue(pName);
            }
        }


        return R.success(pageData);
    }

    /**
     * 设置奖励比例 导出
     * @param sysUserVo
     * @return
     */
   /* @Override
    public R<String> setRewardRote(SysUserVo sysUserVo) {
        SysUserVo userVoByToken = this.getUserVoByToken();
        if(userVoByToken == null){
            return R.error("暂无操作权限");
        }
        Integer level = userVoByToken.getLevel();
        if(level == 3){
            return R.error("暂无操作权限");
        }
        String isPrizePool = userVoByToken.getIsPrizePool();
        if("1".equals(isPrizePool)){
            return R.success();
        }
        Long currenUserId = userVoByToken.getId();
        Long id = sysUserVo.getId();
        Long pid = sysUserVo.getPid();
        *//*if(level == 2){
            if(currenUserId != pid){
                return R.error("暂无操作权限");
            }
        }*//*
        SysUser sysUser = this.getById(id);
        if(sysUserVo.getRewardRote() != null){
            sysUser.setRewardRote(sysUserVo.getRewardRote());
        }
        if(sysUserVo.getLeadIntoLimit() != null){
            sysUser.setLeadIntoLimit(sysUserVo.getLeadIntoLimit());
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(sysUserVo.getExcelLeadInto())){
            sysUser.setExcelLeadInto(sysUserVo.getExcelLeadInto());
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(sysUserVo.getExcelLeadOut())){
            sysUser.setExcelLeadOut(sysUserVo.getExcelLeadOut());
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(sysUserVo.getLeadOutWithPhone())){
            sysUser.setLeadOutWithPhone(sysUserVo.getLeadOutWithPhone());
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(sysUserVo.getGetAllData())){
            sysUser.setGetAllData(sysUserVo.getGetAllData());
        }

        sysUser.setUpdateDate(new Date());
        boolean isSuccess = this.updateById(sysUser);
        if(isSuccess){
            return R.success();
        }else{
            return R.error("设置失败");
        }
    }
*/
    /**
     * 达人列表
     * @param pageNo
     * @param pageSize
     * @param qudaozhu
     * @param loginName
     * @param name
     * @return
     */
    @Override
    public R<PageData<SysUserVo>> selectDarenListpage(Integer pageNo, Integer pageSize, Long qudaozhu, String loginName, String name) {
        SysUserVo currentUserVo = this.selectUserByToken();
        if(currentUserVo == null){
            return R.error("未登录，无权限");
        }
        Integer level = currentUserVo.getLevel();
        Long currentUserVoId = currentUserVo.getId();

        Page page = new Page(pageNo,pageSize);
        QueryWrapper<SysUserVo> suvQw = new QueryWrapper<>();
        suvQw.eq("user_type","2");
        suvQw.eq("level",3);
        if(qudaozhu != null){
            suvQw.eq("pid",qudaozhu);
        }
        if(level == 2){
            suvQw.eq("pid",currentUserVoId);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(loginName)){
            suvQw.eq("login_name",loginName);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(name)){
            suvQw.eq("name",name);
        }
        this.sysUserDao.selectDarenListpage(page,suvQw);
        PageData pageData = PageData.plusPageToPageData(page);
        List<SysUserVo> dataList = pageData.getData();



        LambdaQueryWrapper<SysUser> suLqw = new LambdaQueryWrapper<>();
        suLqw.in(SysUser::getUserType,"2");
        suLqw.in(SysUser::getLevel, Arrays.asList(1,2));
        List<SysUser> oneTwoLevelUserList = this.list(suLqw);
        Map<Long, SysUser> oneTwoLevelUserMap = oneTwoLevelUserList.stream().collect(Collectors.toMap(SysUser::getId, d -> d, (o, n) -> n));
        for(SysUserVo sysUserVo:dataList){
            String status = sysUserVo.getStatus();
            if("1".equals(status)){
                sysUserVo.setStatusValue("正常");
            }else if("0".equals(status)){
                sysUserVo.setStatusValue("删除");
            }

            Long pid = sysUserVo.getPid();
            SysUser twoLevelUser = oneTwoLevelUserMap.get(pid);
            String qudaozhuValue = "";
            String adminValue = "";
            if(twoLevelUser != null){
                qudaozhuValue = twoLevelUser.getLoginName();
                Long oneLevelUserId = twoLevelUser.getPid();
                SysUser oneLevelUser = oneTwoLevelUserMap.get(oneLevelUserId);
                if(oneLevelUser != null){
                    adminValue = oneLevelUser.getLoginName();
                }
            }
            sysUserVo.setQudaozhuValue(qudaozhuValue);
            sysUserVo.setAdminValue(adminValue);
        }

        return R.success(pageData);
    }


    /**
     * 渠道达人列表
     * @return
     */
    @Override
    public List<SysUserTree> selectQuDaoDaren() {
        SysUserVo sysUserVo = this.selectUserByToken();
        List<SysUserTree> sysUserTreeList = new ArrayList<>();
        if(sysUserVo == null){
            return sysUserTreeList;
        }
        Boolean isAdmin = sysUserVo.getIsAdmin();
        QueryWrapper<SysUserTree> sutQw = new QueryWrapper<>();
        sutQw.eq("user_type","2");
        sysUserTreeList = this.sysUserDao.selectSysUserTree(sutQw);
        List<SysUserTree> parentSysUsetTreeList = new ArrayList<>();
        Long currentUserId = sysUserVo.getId();
        if(isAdmin){
            for(SysUserTree sysUserTree:sysUserTreeList){
                Integer level = sysUserTree.getLevel();
                if(level == 1){
                    parentSysUsetTreeList.add(sysUserTree);
                }
            }
        }else{
            Integer level = sysUserVo.getLevel();
            if(level != null && level == 1){
                for(SysUserTree sysUserTree:sysUserTreeList){
                    Integer level2 = sysUserTree.getLevel();
                    Long pid = sysUserTree.getPid();

                    if(level2 == 2 && pid.toString().equals(currentUserId.toString())){

                        parentSysUsetTreeList.add(sysUserTree);
                    }
                }
            }else if(level != null && level == 2){
                List<SysUserTree> level2UserTreeList = new ArrayList<>();
                for(SysUserTree sysUserTree:sysUserTreeList){
                    Integer level2 = sysUserTree.getLevel();
                    Long pid = sysUserTree.getPid();

                    if(level2 == 3){

                        if(pid.toString().equals(currentUserId.toString())){
                            level2UserTreeList.add(sysUserTree);
                        }
                    }
                }
                return level2UserTreeList;
            }
        }
        for(SysUserTree sysUserTree:parentSysUsetTreeList){
            List<SysUserTree> child = getChild(sysUserTree.getId(), sysUserTreeList);
            if(child != null && child.size() > 0){
                sysUserTree.setChildren(child);
            }
        }

        return parentSysUsetTreeList;
    }


    private List<SysUserTree> getChild(Long parentId,List<SysUserTree> sysUserTreeList){
        // 子菜单列表
        List<SysUserTree> childList = new ArrayList<>();
        for(SysUserTree sysMenuTree:sysUserTreeList){
            if(sysMenuTree.getPid().toString().equals(parentId.toString())){
                childList.add(sysMenuTree);
            }
        }

        // 遍历 获取子菜单的子菜单
        for (SysUserTree menu : childList) {
            List<SysUserTree> child = getChild(menu.getId(), sysUserTreeList);
            if(child != null && child.size() > 0){
                menu.setChildren(child);
            }

        }
        //递归出口 childList长度为0
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    @Override
    public R<String> updateDailiUser(SysUserVo sysUserVo) {
        SysUserVo currentSysUserVo = this.getUserVoByToken();
        if(currentSysUserVo == null){
            return R.error("未登录，无权限");
        }
        Integer level = currentSysUserVo.getLevel();
        if(level != 1 && level != 2){
            return R.error("无权限");
        }

        String currentSysUserVoLoginName = currentSysUserVo.getLoginName();
        Date nowTime = new Date();
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserVo,sysUser);
        sysUser.setUpdateDate(nowTime);
        sysUser.setUpdateUser(currentSysUserVoLoginName);
        boolean isSuccess = this.updateById(sysUser);
        if(isSuccess){
            return R.success();
        }else{
            return R.error("操作失败");
        }
    }

    // 编辑渠道主
    @Override
    public R<String> updateQudaozhu(SysUserVo sysUserVo) {
        SysUserVo currentSysUserVo = this.getUserVoByToken();
        if(currentSysUserVo == null){
            return R.error("未登录，无权限");
        }
        Integer level = currentSysUserVo.getLevel();
        if(level != 1){
            return R.error("无权限");
        }
        Long currentSysUserVoId = currentSysUserVo.getId();
        String currentLoginName = currentSysUserVo.getLoginName();
        Date nowTime = new Date();
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserVo,sysUser);
        sysUser.setUpdateDate(nowTime);
        sysUser.setUpdateUser(currentLoginName);
        boolean isSuccess = this.updateById(sysUser);

        if(isSuccess){
            return R.success();
        }else{
            return R.error("操作失败");
        }
    }


    @Override
    public R<List<SysUser>> selectQudaoZhuList() {
        SysUserVo sysUserVo = this.getUserVoByToken();
        if(sysUserVo == null){
            return R.error("未登录，无权限");
        }
        List<SysUser> returnList = new ArrayList<>();
        Integer level = sysUserVo.getLevel();
        if(level == 2 ){
            returnList.add(sysUserVo);
            return R.success(returnList);
        }
        if(level == 3){
            return R.error("无权限");
        }
        Long currentUserId = sysUserVo.getId();
        LambdaQueryWrapper<SysUser> suLqw = new LambdaQueryWrapper<>();
        if(level == 1){
            suLqw.eq(SysUser::getPid,currentUserId);
        }
        suLqw.eq(SysUser::getUserType,"2");
        suLqw.eq(SysUser::getLevel,2);
        returnList = this.list(suLqw);

        return R.success(returnList);
    }

    // 注册
    @Override
    public R<String> register(SysUserVo sysUserVo) {
        String phone = sysUserVo.getPhone();
        LambdaQueryWrapper<SysUser> suLqw = new LambdaQueryWrapper<>();
        suLqw.eq(SysUser::getPhone,phone);

        SysUser sysUser = this.getOne(suLqw, Boolean.FALSE);
        if(sysUser != null){
            return R.error("当前用户已经存在");
        }

        String baseStr = "0123456789";

        LambdaQueryWrapper<SysUser> suLqw2 = new LambdaQueryWrapper<>();
        suLqw2.select(SysUser::getYaoqingma);
        suLqw2.isNotNull(SysUser::getYaoqingma);
        List<SysUser> nativeYaoqingmUserList = this.list(suLqw2);
        Set<String> oldYaoqingmaSet = new HashSet<>();
        for(SysUser sysUser1:nativeYaoqingmUserList){
            oldYaoqingmaSet.add(sysUser1.getYaoqingma());
        }
        String newYaoqingma = RandomUtil.randomString(baseStr, 6);

        while (!oldYaoqingmaSet.add(newYaoqingma)){
            newYaoqingma = RandomUtil.randomString(baseStr, 6);
        }


        String yaoqingma = sysUserVo.getYaoqingma();
        suLqw.clear();
        suLqw.eq(SysUser::getYaoqingma,yaoqingma);
        suLqw.eq(SysUser::getStatus,StatusEnum.OK.getCode());
        SysUser yaoqingUser = this.getOne(suLqw, Boolean.FALSE);
        if(yaoqingUser == null){
            return R.error("邀请码错误");
        }

        String qrCode = "";
        qrCode = this.wechatAppletService.getUnlimitedQRCode("wx7bd68c82356a3f87", "258684f2a8faa47e1ce55969a1916df0", "pages/index/register", newYaoqingma);
        String appQrCode = "";
        try {
            appQrCode = this.caoLiaoService.createPrivateD4QrCode(newYaoqingma);
        }catch (Exception e){
            e.printStackTrace();
        }
        /*log.info("[微信 scheme 码]  : {}",openLinkUrl);
        R<String> uploadResult = this.qrCodeService.generateQRCodeImage(openLinkUrl, 350, 350, newYaoqingma);
*/
        /*if(uploadResult != null && uploadResult.getCode() == 0){
            qrCode = uploadResult.getMsg();
        }*/
        String isPrizePool = yaoqingUser.getIsPrizePool();
        String requestIp = IpAddressUtil.getRequestIp();
        Date nowTime = new Date();
        sysUser = new SysUser();
        sysUser.setRevision(0);
        sysUser.setCreateDate(nowTime);
        sysUser.setUpdateDate(nowTime);
        sysUser.setCreateUser(sysUserVo.getLoginName());
        sysUser.setUpdateUser(sysUserVo.getLoginName());
        sysUser.setSortNum(0);
        sysUser.setStatus(StatusEnum.OK.getCode());
        sysUser.setLoginName(sysUserVo.getLoginName());
        sysUser.setUserType("2");
        sysUser.setPhone(phone);
        sysUser.setHeaderUrl("https://mdhw.oss-cn-hangzhou.aliyuncs.com/jiazhuangTouxiang/headerurl_20240918150446.jpg");

        sysUser.setLoginName(sysUserVo.getLoginName());
        sysUser.setQrCode(qrCode);
        sysUser.setAppQrCode(appQrCode);
        String salt = EncryptUtil.getRandomSalt();
        sysUser.setZhituirenshu(0);
        String pwd = EncryptUtil.encrypt(sysUserVo.getPassword(), salt);

        sysUser.setSalt(salt);
        sysUser.setPassword(pwd);
        sysUser.setPhone(phone);
        //sysUser.setRewardRote(BigDecimal.ZERO);
        //sysUser.setLeadIntoLimit(0);
        //sysUser.setExcelLeadOut("0");
        //sysUser.setExcelLeadInto("0");
        //sysUser.setLeadOutWithPhone("0");
        //sysUser.setGetAllData("0");
        sysUser.setIsPrizePool(isPrizePool);
        sysUser.setIsOpen("1");
        sysUser.setYaoqingma(newYaoqingma);
        sysUser.setLoginName(phone);
        sysUser.setParentZhizhunUserId(yaoqingUser.getParentZhizhunUserId());
        sysUser.setIsZhizhun("0");
        sysUser.setIsFective("0");
        sysUser.setBalance(BigDecimal.ZERO);
        PrizePoolSetVo prizePoolSetVo = this.sysDictDataService.selectPrizePoolSet();


        sysUser.setPid(yaoqingUser.getId());
        boolean isSuccess = this.save(sysUser);

        LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
        saLqw.eq(SysAccount::getUserId,yaoqingUser.getId());
        SysAccount pSysAccount = this.sysAccountService.getOne(saLqw, Boolean.FALSE);



        Long userId = sysUser.getId();
        SysAccount sysAccount = new SysAccount();
        sysAccount.setRevision(0);
        sysAccount.setUserId(userId);
        sysAccount.setRegisterIp(requestIp);
        sysAccount.setXianCount(0);
        if(pSysAccount != null && org.apache.commons.lang.StringUtils.isNotBlank(pSysAccount.getXianStr())){
            String xianStr = pSysAccount.getXianStr();
            xianStr = xianStr +userId+",";
            sysAccount.setXianStr(xianStr);
        }

        this.sysAccountService.save(sysAccount);


        if(isSuccess){
            return R.success();
        }else{
            return R.error("新增失败");
        }
    }

    @Override
    public R<String> sendCode(String phone, String type, Boolean aTrue) {
        String key = CacheKeyContants.AOZHONG_MSG_CODE+type+":"+phone;

        Long expireTime = redisUtil.getExpire(key);
        if (expireTime >= 240) {
            return R.error("请勿频繁操作");
        }
        String s = RandomUtil.randomNumbers(6);
        Map<String, String> mapParams = new HashMap<>();
        mapParams.put("code", s);
        String mapParamsJson = JSONObject.toJSONString(mapParams);
        R<String> result = this.smsAoZhongService.sendAoZhongYzmSMS(s, phone);
            /*MessageExposer<String> result = SmsAliUtil.sendAliSMS(aliSMSProperties.getAppKey(), aliSMSProperties.getSecret(),
                    phone, aliSMSProperties.getSignName(), aliSMSProperties.getCaptcha(), mapParamsJson);*/
//            String msg = String.format(sendMsgCode,s);
//            MessageExposer<String> result = smsAoZhongService.cxmAoZhongCodeSMS(msg,phone);
        Integer code = result.getCode();
        System.out.println(code);
        if (code == 0) {
            // 缓存设置有效期5分钟
            redisUtil.set(key, s, 300);
            return R.success("验证码已发送");
        }

        return R.error("发送失败，请重试");
    }
    // 检查验证码是否正确
    @Override
    public R<String> checkCode(String phone, String code, String type) {
        String key = CacheKeyContants.AOZHONG_MSG_CODE+type+":"+phone;
        Object redisCode = this.redisUtil.get(key);
        if(redisCode == null){
            return R.error("验证码已过期，请重新发送！");
        }
        String redisCodeStr = (String) redisCode;
        if(!redisCodeStr.equals(code)){
            return R.error("验证码错误！");
        }
        return R.success();
    }


    @Override
    public List<LianheShangjiaVo> selectLianheShangjiaList() {
        List<LianheShangjiaVo> returnList = new ArrayList<>();
        LianheShangjiaVo lianheShangjiaVo1 = new LianheShangjiaVo();
        lianheShangjiaVo1.setDianzan(186);
        lianheShangjiaVo1.setTitle("现代简约");
        lianheShangjiaVo1.setFabuDate("2024-09-11");
        lianheShangjiaVo1.setIsFabu("已发布");
        lianheShangjiaVo1.setShow(196);
        lianheShangjiaVo1.setPinglun(172);
        lianheShangjiaVo1.setZhuImage("https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726032945081_TXncrpNM.jpg");
        lianheShangjiaVo1.setDetails("<h1 class=\"ql-align-center\"><strong style=\"color: rgb(102, 185, 102);\">简约而不失温馨的雅致空间</strong></h1><p class=\"ql-align-center\"><br></p><p><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726032978821_r3TRfBs4.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726032978821_X5pyks5n.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726032978821_tCXSZsBz.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726032978822_NE2BczJf.jpg\"></p>");


        LianheShangjiaVo lianheShangjiaVo2 = new LianheShangjiaVo();
        lianheShangjiaVo2.setDianzan(156);
        lianheShangjiaVo2.setTitle("新中式");
        lianheShangjiaVo2.setFabuDate("2024-09-11");
        lianheShangjiaVo2.setIsFabu("已发布");
        lianheShangjiaVo2.setShow(201);
        lianheShangjiaVo2.setPinglun(177);
        lianheShangjiaVo2.setZhuImage("https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033388720_D4eFsApS.jpg");
        lianheShangjiaVo2.setDetails("<h1 class=\"ql-align-justify\"><strong style=\"background-color: rgb(240, 102, 102);\">结合现代审美，保留中式风格的沉稳大气，简化造型线条，以中国传统古典文化为背景，营造极具中国古典的稳重与温馨的氛围。</strong></h1><p><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033513601_3zNp2NZD.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033513602_8dHc3R7E.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033513602_4YJeak3B.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033513602_PQnYeKKZ.jpg\"></p>");

        LianheShangjiaVo lianheShangjiaVo3 = new LianheShangjiaVo();
        lianheShangjiaVo3.setDianzan(253);
        lianheShangjiaVo3.setTitle("法式浪漫轻奢");
        lianheShangjiaVo3.setFabuDate("2024-09-11");
        lianheShangjiaVo3.setIsFabu("已发布");
        lianheShangjiaVo3.setShow(185);
        lianheShangjiaVo3.setPinglun(165);
        lianheShangjiaVo3.setZhuImage("https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033805824_Fy8hcBHX.jpg");
        lianheShangjiaVo3.setDetails("<h1 class=\"ql-align-center\"><span style=\"background-color: rgb(250, 204, 204);\">法式浪漫轻奢风格注重简约而不失高级感的设计，通过简单的线条和精致的细节来营造低调的奢华感</span></h1><p><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033758506_X4Rf5Chp.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033758507_XBSrTTFA.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033758507_4p2aZ2Hd.jpg\"><img src=\"https://mdhw.oss-cn-hangzhou.aliyuncs.com/goods/1726033758507_X4QjJkew.jpg\"></p>");
        returnList.add(lianheShangjiaVo1);
        returnList.add(lianheShangjiaVo2);
        returnList.add(lianheShangjiaVo3);
        return returnList;
    }


    @Override
    public R<String> uploadHeaderUrl(MultipartFile uploadFile) {
        SysUserVo sysUserVo = this.selectUserByToken();
        try {
            Date nowTime = new Date();
            Long userId = sysUserVo.getId();
            String jiazhuangTouxiang = "jiazhuangTouxiang/"+DateUtil.formatDate(nowTime, DateUtil.yyyy_mm_dd_hh_mm_ss)+"_"+userId+".PNG";
            InputStream inputStream = uploadFile.getInputStream();
            AliYunOssResult uploadResult = this.aliYunOssServer.upload(inputStream, jiazhuangTouxiang);
            if(uploadResult != null){
                String url = uploadResult.getUrl();
                SysUser sysUser = this.getById(userId);
                sysUser.setHeaderUrl(url);
                this.updateById(sysUser);
                return R.success(uploadResult.getUrl());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public R<String> uploadLiangfangImage(MultipartFile uploadFile,Long id) {
        JiaOrder jiaOrder = this.jiaOrderDao.selectById(id);
        if(jiaOrder == null){
            return R.error("暂无此订单");
        }
        if(!AudiStatusEnum.ADUI_STATUS_5.getCode().equals(jiaOrder.getAudiStatus())){
            return R.error("当前订单暂时无法上传量房截图");
        }
        SysUserVo sysUserVo = this.selectUserByToken();
        if(sysUserVo == null){
            return R.error("未登录");
        }
        Long userVoId = sysUserVo.getId();
        Long orderUserId = jiaOrder.getUserId();
        if(!orderUserId.toString().equals(userVoId.toString())){
            return R.error("无权限");
        }

        try {
            Date nowTime = new Date();
            Long userId = sysUserVo.getId();
            String jiazhuangTouxiang = "liangfangImage/"+DateUtil.formatDate(nowTime, DateUtil.yyyy_mm_dd_hh_mm_ss)+"_"+userId+"_"+id+".PNG";
            InputStream inputStream = uploadFile.getInputStream();
            AliYunOssResult uploadResult = this.aliYunOssServer.upload(inputStream, jiazhuangTouxiang);
            if(uploadResult != null){
                String url = uploadResult.getUrl();


                jiaOrder.setLiangfangImage(url);
                //jiaOrder.setIsLiangfang("1");
                this.jiaOrderDao.updateById(jiaOrder);
                return R.success(uploadResult.getUrl());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {

        BigDecimal a = BigDecimal.ONE;
        BigDecimal b = new BigDecimal("0.60");

        BigDecimal c = BigDecimal.ZERO;

        List<String> kouliangList = new ArrayList<>();
        List<BigDecimal> kouList = new ArrayList<>();
        List<BigDecimal> newkouList = new ArrayList<>();
        for(Integer i = 1; i <= 1055 ;i ++){
            if( i == 56){
                b = new BigDecimal("0.68");
            }
            if (i == 1) {
                c = a.subtract(b);
            }else{
                if(c.compareTo(BigDecimal.ZERO) == 0 || c.compareTo(BigDecimal.ZERO) == -1){
                    c = c.add(BigDecimal.ONE);
                }
                c = c.subtract(b);
            }

            if(i>=56){
                newkouList.add(c);
            }
            // c <= 0;

            kouList.add(c);
        }
        System.out.println(kouList);


        /*List<BigDecimal> newKouList = new ArrayList<>();
        for(Integer i = 56; i <= 1000 ;i ++){
            BigDecimal kou = kouList.get(i);
            newKouList.add(kou);
        }*/
        Integer kouliang = 0;
        Integer shang = 0;
        for(BigDecimal kou : newkouList){
            if(kou.compareTo(BigDecimal.ZERO) == 0 ||kou.compareTo(BigDecimal.ZERO) == -1){
                kouliang++;
            }else{
                shang++;
            }
        }
        System.out.println("扣量 ： " + kouliang);
        System.out.println("上报 :  "+shang);
    }


    @Override
    public R<TuanduiVo> selectTuanduiVo() {
        SysUserVo sysUserVo = this.selectUserByToken();
        if(sysUserVo == null){
            return R.success();
        }

        TuanduiVo tuanduiVo = new TuanduiVo();
        Long userId = sysUserVo.getId();


        Integer youxiaoCount = 0;
        Integer wuxiaoCount = 0;
        Integer tuanduiCount = 0;
        Set<Long> youxiaoSet = new HashSet<>();
        Set<Long> wuxiaoSet = new HashSet<>();

        /*for(JiaOrder jiaOrder:jiaOrderList){
            Long pUserId = jiaOrder.getPUserId();

        }*/


        if(userId.toString().equals("17")){
            tuanduiVo.setYouxiaoCount(1);
            tuanduiVo.setWuxiaoCount(2);
            tuanduiVo.setChengyuanCount(1);
            List<TuanduiInfoVo> youxiao = new ArrayList<>();
            TuanduiInfoVo tuanduiInfoVo1= new TuanduiInfoVo();
            tuanduiInfoVo1.setId(1L);
            tuanduiInfoVo1.setPhone("17755555555");
            tuanduiInfoVo1.setCreateDate(new Date());
            tuanduiInfoVo1.setOrderCount(2);
            youxiao.add(tuanduiInfoVo1);

            List<TuanduiInfoVo> wuxiao = new ArrayList<>();
            TuanduiInfoVo tuanduiInfoVo2= new TuanduiInfoVo();
            tuanduiInfoVo2.setId(2L);
            tuanduiInfoVo2.setPhone("17755556666");
            tuanduiInfoVo2.setCreateDate(new Date());
            tuanduiInfoVo2.setOrderCount(3);
            wuxiao.add(tuanduiInfoVo2);

            TuanduiInfoVo tuanduiInfoVo3= new TuanduiInfoVo();
            tuanduiInfoVo3.setId(3L);
            tuanduiInfoVo3.setPhone("17755557777");
            tuanduiInfoVo3.setCreateDate(new Date());
            tuanduiInfoVo3.setOrderCount(2);
            wuxiao.add(tuanduiInfoVo3);
            tuanduiVo.setYouxiaoTuandui(youxiao);
            tuanduiVo.setWuxiaoTuandui(wuxiao);

            List<TuanduiInfoVo> chengyua = new ArrayList<>();
             TuanduiInfoVo tuanduiInfoVo4= new TuanduiInfoVo();
            tuanduiInfoVo4.setId(4L);
            tuanduiInfoVo4.setPhone("17755557777");
            tuanduiInfoVo4.setCreateDate(new Date());
            tuanduiInfoVo4.setOrderCount(2);
            chengyua.add(tuanduiInfoVo4);
            tuanduiVo.setChengyuanTuandui(chengyua);
        }

        Date nowTime = new Date();

        LambdaQueryWrapper<JiaOrder> joLqw = new LambdaQueryWrapper<>();
        joLqw.select(JiaOrder::getId,JiaOrder::getAudiStatus,JiaOrder::getUserId,JiaOrder::getOrderPrice,JiaOrder::getIsLiangfang,JiaOrder::getLiangfangDate);

        joLqw.eq(JiaOrder::getPUserId,userId);
        joLqw.eq(JiaOrder::getStatus,StatusEnum.OK.getCode());
        joLqw.eq(JiaOrder::getIsShangwu,"0");
        List<JiaOrder> jiaOrderList = this.jiaOrderDao.selectList(joLqw);

        for(JiaOrder jiaOrder:jiaOrderList){
            String isLiangfang = jiaOrder.getIsLiangfang();
            Long itemUserId = jiaOrder.getUserId();

            if("1".equals(isLiangfang)){
                // 有效
                youxiaoSet.add(itemUserId);
            }
            if("0".equals(isLiangfang)){
                // 无效
                wuxiaoSet.add(itemUserId);
            }
        }

        wuxiaoSet.removeAll(youxiaoSet);
        wuxiaoCount = wuxiaoSet.size();
        youxiaoCount = youxiaoSet.size();

        if(wuxiaoCount == 0){
            wuxiaoSet.add(-11L);
        }
        if(youxiaoCount == 0){
            youxiaoSet.add(-11L);
        }

        QueryWrapper<SysUser> youxiaoUserLqw = new QueryWrapper<>();
        youxiaoUserLqw.select("id","phone","create_date");
        youxiaoUserLqw.in("id",youxiaoSet);
        List<TuanduiInfoVo> youxiaoUserList = this.sysUserDao.selectTuanduiUserInfo(youxiaoUserLqw);

        LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
        saLqw.select(SysAccount::getId,SysAccount::getUserId,SysAccount::getXianStr);
        saLqw.like(SysAccount::getXianStr,"%,"+userId+",%");
        List<SysAccount> sysAccountList = this.sysAccountService.list(saLqw);


        Date firstDayOfMonth = DateUtil.getFirstDayOfMonth(nowTime);
        String yyyymmdd = DateUtil.formatDate(firstDayOfMonth, DateUtil.YYYY_MM_DD);
        String yyyymm = DateUtil.formatDate(firstDayOfMonth,DateUtil.YYYY_MM);
        String ddStr = yyyymmdd.substring(8);
        Integer dd = Integer.parseInt(ddStr);
        for(TuanduiInfoVo tuanduiInfoVo:youxiaoUserList){
            Long tuanduiUserId = tuanduiInfoVo.getId();
            String firstXianstr = userId+","+tuanduiUserId+",";
            //log.info("firstXianstr:{}",firstXianstr);
            Set<Long> itemUserIdSet = new HashSet<>();
            itemUserIdSet.add(tuanduiUserId);
            for(SysAccount sysAccount:sysAccountList){
                String xianStr = sysAccount.getXianStr();
                int index = xianStr.indexOf(firstXianstr);
                if(index > 0){
                    index = index + firstXianstr.length();

                    String itemXianStr = xianStr.substring(index);
                    ///log.info("xianStr:{}   firstXianstr : {}  index :{}  itemXianStr : {}",xianStr,firstXianstr,index,itemXianStr);
                    if(org.apache.commons.lang.StringUtils.isNotBlank(itemXianStr)){
                        String[] itemXianStrArr = itemXianStr.split(",");
                        for(Integer a=0;a<itemXianStrArr.length;a++){
                            String itemXianStrA = itemXianStrArr[a];
                            if(org.apache.commons.lang.StringUtils.isNotBlank(itemXianStrA)){
                                itemUserIdSet.add(Long.parseLong(itemXianStrA));
                            }
                        }
                    }
                }

            }
            //log.info("tuanduiUserId  : {}   ,itemUserIdSet : {}",tuanduiUserId,JSONObject.toJSONString(itemUserIdSet));
            QueryWrapper<JiaOrderVo> jovQw = new QueryWrapper<>();
            /*if(dd >= 15){
                jovQw.ge("liangfang_date",yyyymm+"-15 00:00:00");
            }else{
                jovQw.ge("liangfang_date",firstDayOfMonth);
            }*/
            jovQw.ge("liangfang_date","2024-11-15 00:00:00");
            jovQw.eq("is_shangwu","0");
            jovQw.in("user_id",itemUserIdSet);
            jovQw.eq("is_liangfang","1");
            List<JiaOrderVo> sumOrderPriceJiaOrderVos = this.jiaOrderDao.selectSumOrderPriceByIds(jovQw);
            BigDecimal shouyi = BigDecimal.ZERO;
            if(sumOrderPriceJiaOrderVos != null && sumOrderPriceJiaOrderVos.size() > 0){
                JiaOrderVo sumOrderPriceJiaOrderVo = sumOrderPriceJiaOrderVos.get(0);
                if(sumOrderPriceJiaOrderVo != null){
                    if(sumOrderPriceJiaOrderVo.getOrderPrice() != null){
                        shouyi = sumOrderPriceJiaOrderVo.getOrderPrice();
                    }
                }
            }
            tuanduiInfoVo.setShouyi(shouyi);
        }


        QueryWrapper<SysUser> wuxiaoUserLqw = new QueryWrapper<>();
        wuxiaoUserLqw.select("id","phone","create_date");
        wuxiaoUserLqw.in("id",wuxiaoSet);
        //wuxiaoUserLqw.eq("status",StatusEnum.OK.getCode());
        List<TuanduiInfoVo> wuxiaoUserList = this.sysUserDao.selectTuanduiUserInfo(wuxiaoUserLqw);

        QueryWrapper<SysUser> tuanduiUserLqw = new QueryWrapper<>();
        tuanduiUserLqw.select("id","phone","create_date");
        tuanduiUserLqw.in("pid",userId);
        //tuanduiUserLqw.eq("status",StatusEnum.OK.getCode());
        List<TuanduiInfoVo> tuanduiUserList = this.sysUserDao.selectTuanduiUserInfo(tuanduiUserLqw);
        if(tuanduiUserList != null){
            tuanduiCount = tuanduiUserList.size();
        }
        for(TuanduiInfoVo tuanduiInfoVo:tuanduiUserList){
            Long tuanduiUserId = tuanduiInfoVo.getId();
            String firstXianstr = userId+","+tuanduiUserId+",";
            //log.info("firstXianstr:{}",firstXianstr);
            Set<Long> itemUserIdSet = new HashSet<>();
            itemUserIdSet.add(tuanduiUserId);
            for(SysAccount sysAccount:sysAccountList){
                String xianStr = sysAccount.getXianStr();
                int index = xianStr.indexOf(firstXianstr);
                if(index > 0){
                    index = index + firstXianstr.length();

                    String itemXianStr = xianStr.substring(index);
                    //log.info("xianStr:{}   firstXianstr : {}  index :{}  itemXianStr : {}",xianStr,firstXianstr,index,itemXianStr);
                    if(org.apache.commons.lang.StringUtils.isNotBlank(itemXianStr)){
                        String[] itemXianStrArr = itemXianStr.split(",");
                        for(Integer a=0;a<itemXianStrArr.length;a++){
                            String itemXianStrA = itemXianStrArr[a];
                            if(org.apache.commons.lang.StringUtils.isNotBlank(itemXianStrA)){
                                itemUserIdSet.add(Long.parseLong(itemXianStrA));
                            }
                        }
                    }
                }

            }
            //log.info("tuanduiUserId  : {}   ,itemUserIdSet : {}",tuanduiUserId,JSONObject.toJSONString(itemUserIdSet));
            QueryWrapper<JiaOrderVo> jovQw = new QueryWrapper<>();
            /*if(dd >= 15){
                jovQw.ge("liangfang_date",yyyymm+"-15 00:00:00");
            }else{
                jovQw.ge("liangfang_date",firstDayOfMonth);
            }*/
            jovQw.ge("liangfang_date","2024-11-15 00:00:00");

            jovQw.in("user_id",itemUserIdSet);
            jovQw.eq("is_liangfang","1");


            List<JiaOrderVo> sumOrderPriceJiaOrderVos = this.jiaOrderDao.selectSumOrderPriceByIds(jovQw);
            BigDecimal shouyi = BigDecimal.ZERO;
            if(sumOrderPriceJiaOrderVos != null && sumOrderPriceJiaOrderVos.size() > 0){
                //log.info("sumOrderPriceJiaOrderVos : {} ",JSONObject.toJSONString(sumOrderPriceJiaOrderVos) );
                JiaOrderVo sumOrderPriceJiaOrderVo = sumOrderPriceJiaOrderVos.get(0);
                if(sumOrderPriceJiaOrderVo != null){
                    if(sumOrderPriceJiaOrderVo.getOrderPrice() != null){
                        shouyi = sumOrderPriceJiaOrderVo.getOrderPrice();
                    }
                }
            }
            tuanduiInfoVo.setShouyi(shouyi);
        }

        tuanduiVo.setYouxiaoTuandui(youxiaoUserList);
        tuanduiVo.setWuxiaoTuandui(wuxiaoUserList);
        tuanduiVo.setYouxiaoCount(youxiaoCount);
        tuanduiVo.setWuxiaoCount(wuxiaoCount);
        tuanduiVo.setChengyuanCount(tuanduiCount);
        tuanduiVo.setChengyuanTuandui(tuanduiUserList);

        BigDecimal totalOrderPrice = BigDecimal.ZERO;
        /*for(JiaOrder jiaOrder : jiaOrderList){
            BigDecimal orderPrice = jiaOrder.getOrderPrice();
            totalOrderPrice = totalOrderPrice.add(orderPrice);
        }
        tuanduiVo.setTotalOrderPrice(totalOrderPrice);*/
        LambdaQueryWrapper<JiaOrder> jo2Lqw = new LambdaQueryWrapper<>();
        /*if(dd >= 15){
            jo2Lqw.ge(JiaOrder::getLiangfangDate,yyyymm+"-15 00:00:00");
        }else{
            jo2Lqw.ge(JiaOrder::getLiangfangDate,firstDayOfMonth);
        }*/
        jo2Lqw.ge(JiaOrder::getLiangfangDate,"2024-11-15 00:00:00");

        jo2Lqw.eq(JiaOrder::getUserId,userId);
        jo2Lqw.eq(JiaOrder::getIsLiangfang,"1");

        List<JiaOrder> jiaOrderList1 = this.jiaOrderDao.selectList(jo2Lqw);
        for(JiaOrder jiaOrder:jiaOrderList1){
            totalOrderPrice = totalOrderPrice.add(jiaOrder.getOrderPrice());
        }
        for(TuanduiInfoVo tuanduiInfoVo:tuanduiUserList){
            BigDecimal shouyi = tuanduiInfoVo.getShouyi();
            totalOrderPrice = totalOrderPrice.add(shouyi);
        }
        tuanduiVo.setTotalOrderPrice(totalOrderPrice);
        return R.success(tuanduiVo);
    }

    /**
     * 修改支付密码
     * @param sysUserVo
     * @return
     */
    @Override
    public R<String> updatePayPwd(SysUserVo sysUserVo) {

        String payPwd = sysUserVo.getPayPwd();
        SysUserVo sysUserVo1 = this.selectUserByToken();
        if(sysUserVo1 == null){
            return R.error("无权限");
        }
        Long id = sysUserVo1.getId();
        SysUser sysUser = this.getById(id);
        String salt = sysUser.getSalt();
        String saltPwd = EncryptUtil.encrypt(payPwd, salt);
        sysUser.setPayPassword(saltPwd);
        log.info("[修改支付密码] {}",JSONObject.toJSONString(sysUser));
        boolean isSuccess = this.updateById(sysUser);
        if(isSuccess){
            return R.success();
        }else{
            return R.error("操作失败");
        }

    }



    @Override
    public R<String> updatePwd(SysUserVo sysUserVo) {
        String password = sysUserVo.getPassword();
        SysUserVo sysUserVo1 = this.selectUserByToken();
        if(sysUserVo1 == null){
            return R.error("无权限");
        }
        Long id = sysUserVo1.getId();
        SysUser sysUser = this.getById(id);
        String salt = sysUser.getSalt();
        String saltPwd = EncryptUtil.encrypt(password, salt);
        sysUser.setPassword(saltPwd);
        boolean isSuccess = this.updateById(sysUser);
        if(isSuccess){
            return R.success();
        }else{
            return R.error("操作失败");
        }

    }

    @Override
    public R<PageData<SysUserVo>> selectRegisterListPage(Integer pageNo, Integer pageSize, String startTime, String endTime,Long levelId,String phone,Long id,String pPhone) {
        SysUserVo sysUserVo = this.selectUserByToken();
        if(sysUserVo == null){
            return R.success();
        }

        QueryWrapper<SysUserVo> suvQw = new QueryWrapper<>();
        //suvQw.select("id","phone","createDate","yaoqingma","balance","levelId");
        //suvQw.eq("status",StatusEnum.OK.getCode());
        suvQw.eq("user_type","2");
        if(id != null){
            suvQw.eq("id",id);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(pPhone)){
            Long userId = null;
            if(pPhone.length() == 11){
                LambdaQueryWrapper<SysUser> suLqw = new LambdaQueryWrapper<>();
                suLqw.eq(SysUser::getPhone,pPhone);
                SysUser sysUser = this.getOne(suLqw, Boolean.FALSE);
                if(sysUser != null){
                    userId = sysUser.getId();
                }
            }else{
                userId = Long.parseLong(pPhone);
            }
            suvQw.eq("pid",userId);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(startTime)){
            suvQw.ge("create_date",startTime);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(endTime)){
            suvQw.le("create_date",endTime);
        }
        if(levelId != null && !"0".equals(levelId.toString())){

            suvQw.eq("level_id",levelId);
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(phone)){
            suvQw.eq("phone",phone);
        }
        suvQw.orderByDesc("id");
        Page page = new Page(pageNo,pageSize);
        this.sysUserDao.selectDarenListpage(page,suvQw);
        PageData pageData = PageData.plusPageToPageData(page);
        List<SysUserVo> dataList = pageData.getData();

        List<Long> pUserIdList = new ArrayList<>();
        pUserIdList.add(-11L);
        for(SysUserVo sysUserVo1:dataList){
            pUserIdList.add(sysUserVo1.getPid());
            Long levelId1 = sysUserVo1.getLevelId();
            if(levelId1 == null){
                sysUserVo1.setLevelValue("");
                continue;
            }

            if("1".equals(levelId1.toString())){
                sysUserVo1.setLevelValue("黄金");
            }else if("2".equals(levelId1.toString())){
                sysUserVo1.setLevelValue("白金");
            }else if("3".equals(levelId1.toString())){
                sysUserVo1.setLevelValue("钻石");
            }else if("4".equals(levelId1.toString())){
                sysUserVo1.setLevelValue("初级合伙人");
            }else if("5".equals(levelId1.toString())){
                sysUserVo1.setLevelValue("中级合伙人");
            }else if("6".equals(levelId1.toString())){
                sysUserVo1.setLevelValue("高级合伙人");
            }

            if(StatusEnum.OK.getCode().equals(sysUserVo1.getStatus())){
                sysUserVo1.setStatusValue(StatusEnum.OK.getMessage());
            }else if(StatusEnum.DONGJIE.getCode().equals(sysUserVo1.getStatus())){
                sysUserVo1.setStatusValue(StatusEnum.DONGJIE.getMessage());
            }
        }

        LambdaQueryWrapper<SysUser> suLqw =new LambdaQueryWrapper<>();
        suLqw.in(SysUser::getId,pUserIdList);
        List<SysUser> pSysUserList = this.list(suLqw);
        Map<Long, SysUser> pSysUserMap = pSysUserList.stream().collect(Collectors.toMap(SysUser::getId, d -> d, (o, n) -> n));
        for(SysUserVo sysUserVo1:dataList){
            Long pid = sysUserVo1.getPid();
            SysUser sysUser = pSysUserMap.get(pid);
            if(sysUser != null){
                String pUserPhone = sysUser.getPhone();
                sysUserVo1.setZhituirenPhone(pUserPhone);
            }
        }

        return R.success(pageData);
    }


    // 设置邀请码
    @Override
    public R<String> setYaoqingma(SysUserVo sysUserVo) {
        Long userVoId = sysUserVo.getId();
        if(userVoId == null){
            return R.error("操作失败");
        }
        String yaoqingma = sysUserVo.getYaoqingma();
        LambdaQueryWrapper<SysUser> suLqw = new LambdaQueryWrapper<>();
        suLqw.eq(SysUser::getYaoqingma,yaoqingma);
        suLqw.eq(SysUser::getStatus,StatusEnum.OK.getCode());
        SysUser oldSysUser = this.getOne(suLqw, Boolean.FALSE);
        if(oldSysUser != null){
            return R.error(yaoqingma+"  该邀请码已存在");
        }
        SysUser sysUser = this.getById(userVoId);
        sysUser.setYaoqingma(yaoqingma);
        String qrCode = this.wechatAppletService.getUnlimitedQRCode("wx7bd68c82356a3f87", "258684f2a8faa47e1ce55969a1916df0", "pages/index/index", yaoqingma);
        sysUser.setQrCode(qrCode);
        sysUser.setUpdateDate(new Date());
        boolean isSuccess = this.updateById(sysUser);
        if(isSuccess){
            return R.success();
        }else {
            return R.error("设置失败");
        }
    }


    public R<String> updateXian(){

        List<SysUser> sysUserList = this.list();
        Map<Long, SysUser> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getId, d -> d, (o, n) -> n));
        List<SysAccount> sysAccountList = this.sysAccountService.list();
        Map<Long, SysAccount> sysAccountMap = sysAccountList.stream().collect(Collectors.toMap(SysAccount::getUserId, d -> d, (o, n) -> n));
        for(SysUser sysUser:sysUserList){
            Long pid = sysUser.getPid();
            if(pid == null || "0".equals(pid.toString())){
                continue;
            }
            Long userId = sysUser.getId();
            String xianStr = userId.toString();
            xianStr = pid +","+xianStr;

            SysAccount sysAccount = sysAccountMap.get(userId);

            while (true){
                SysUser pSysUser = sysUserMap.get(pid);
                if(pSysUser == null){
                    break;
                }
                Long pid2 = pSysUser.getPid();
                if(pid2 == null || "0".equals(pid2) || "1".equals(pid2)){
                    break;
                }
                xianStr = pid2+","+xianStr;
                pid = pid2;

            }

            if(xianStr.indexOf("0,") == 0){
                xianStr = xianStr.substring(2);
            }
            xianStr+=",";
            xianStr = ","+xianStr;
            sysAccount.setXianStr(xianStr);
            this.sysAccountService.updateById(sysAccount);
        }
        return null;
    }


    @Override
    public R<String> updateXianLevelCount() {
        List<SysUser> sysUserList = this.list();
        Map<Long, SysUser> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getId, d -> d, (o, n) -> n));


        List<SysAccount> sysAccountList = this.sysAccountService.list();
        Map<Long, SysAccount> sysAccountMap = sysAccountList.stream().collect(Collectors.toMap(SysAccount::getUserId, d -> d, (o, n) -> n));
        for(SysAccount sysAccount:sysAccountList){
            Long userId = sysAccount.getUserId();
            SysUser sysUser = sysUserMap.get(userId);
            if(sysUser == null){
                continue;
            }
            Long levelId = sysUser.getLevelId();
            if (levelId == null || levelId <=0){
                continue;
            }
            String levelIdStr = levelId.toString();
            String xianStr = sysAccount.getXianStr();
            if(org.apache.commons.lang.StringUtils.isBlank(xianStr)){
                continue;
            }
            String[] split = xianStr.split(",");

            for(String xianItem:split){
                if(org.apache.commons.lang.StringUtils.isNotBlank(xianStr)){

                    if(!xianItem.equals(userId.toString()) && NumberUtil.isNumber(xianItem)){
                        Long accountUserId = Long.parseLong(xianItem);
                        SysAccount sysAccount1 = sysAccountMap.get(accountUserId);
                        if(sysAccount1 != null){
                            Integer level1Count = sysAccount1.getLevel1Count();
                            Integer level2Count = sysAccount1.getLevel2Count();
                            Integer level3Count = sysAccount1.getLevel3Count();
                            Integer level4Count = sysAccount1.getLevel4Count();
                            Integer level5Count = sysAccount1.getLevel5Count();
                            Integer level6Count = sysAccount1.getLevel6Count();
                            if("1".equals(levelIdStr)){
                                level1Count += 1;
                            }else if("2".equals(levelIdStr)){
                                level2Count += 1;
                            }else if("3".equals(levelIdStr)){
                                level3Count += 1;
                            }else if("4".equals(levelIdStr)){
                                level4Count += 1;
                            }else if("5".equals(levelIdStr)){
                                level5Count += 1;
                            }else if("6".equals(levelIdStr)){
                                level6Count += 1;
                            }
                            sysAccount1.setLevel1Count(level1Count);
                            sysAccount1.setLevel2Count(level2Count);
                            sysAccount1.setLevel3Count(level3Count);
                            sysAccount1.setLevel4Count(level4Count);
                            sysAccount1.setLevel5Count(level5Count);
                            sysAccount1.setLevel6Count(level6Count);
                            sysAccountMap.put(accountUserId,sysAccount1);
                        }
                    }
                }
            }
        }

        Set<Long> sysAccountIdSet = sysAccountMap.keySet();
        for(Long userId:sysAccountIdSet){
            SysAccount sysAccount = sysAccountMap.get(userId);
            this.sysAccountService.updateById(sysAccount);
        }
        return null;
    }

    @Override
    public R<List<SysUser>> selectSysUserGuanxi(Long id) {
        LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
        saLqw.eq(SysAccount::getUserId,id);
        SysAccount sysAccount = this.sysAccountService.getOne(saLqw, Boolean.FALSE);
        String xianStr = sysAccount.getXianStr();
        String[] xianStrArr = xianStr.split(",");
        List<Long> userIdList = new ArrayList<>();
        for(String xianStrItem:xianStrArr){
            if(org.apache.commons.lang.StringUtils.isNotBlank(xianStrItem) && NumberUtil.isNumber(xianStrItem)){
                userIdList.add(Long.parseLong(xianStrItem));
            }
        }
        LambdaQueryWrapper<SysUser> suLqw = new LambdaQueryWrapper<>();
        suLqw.in(SysUser::getId,userIdList);
        suLqw.orderByAsc(SysUser::getId);
        List<SysUser> sysUserList = this.list(suLqw);

        return R.success(sysUserList);
    }

    /**
     * 冻结用户
     * @param sysUserVo
     * @return
     */
    @Override
    public R<String> dongjieUser(SysUserVo sysUserVo) {
        SysUserVo currentUser = this.selectUserByToken();
        if(currentUser == null){
            return R.error("未登录，无权限！");
        }
        Long userVoId = sysUserVo.getId();
        SysUser sysUser = this.getById(userVoId);
        if(sysUser == null){
            return R.error("当前用户不存在！");
        }
        String status = sysUser.getStatus();
        if(StatusEnum.DONGJIE.getCode().equals(status)){
            // 解冻
            Date nowTime = new Date();
            sysUser.setStatus(StatusEnum.OK.getCode());
            sysUser.setUpdateDate(nowTime);
            sysUser.setUpdateUser(currentUser.getPhone());
            sysUser.setIsOpen("1");
            boolean isSuccess = this.updateById(sysUser);
            if(isSuccess){
                // TODO 修改 account
                LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
                saLqw.eq(SysAccount::getUserId,userVoId);
                SysAccount sysAccount = this.sysAccountService.getOne(saLqw, Boolean.FALSE);
                if(sysAccount != null){
                    sysAccount.setStatus(StatusEnum.OK.getCode());
                    sysAccount.setUpdateDate(nowTime);
                    boolean sysAccountSuccess = this.sysAccountService.updateById(sysAccount);
                }
                return R.success();
            }else{
                return R.error("操作失败");
            }
        }
        Date nowTime = new Date();
        sysUser.setStatus(StatusEnum.DONGJIE.getCode());
        sysUser.setUpdateDate(nowTime);
        sysUser.setUpdateUser(currentUser.getPhone());
        sysUser.setIsOpen("0");

        boolean isSuccess = this.updateById(sysUser);
        BigDecimal balance1 = sysUser.getBalance();
        if(isSuccess){
            // TODO 修改 account
            LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
            saLqw.eq(SysAccount::getUserId,userVoId);
            SysAccount sysAccount = this.sysAccountService.getOne(saLqw, Boolean.FALSE);
            if(sysAccount != null){
                sysAccount.setStatus(StatusEnum.DONGJIE.getCode());
                sysAccount.setUpdateDate(nowTime);
                boolean sysAccountSuccess = this.sysAccountService.updateById(sysAccount);
            }

            // TODO 提现记录收回
            LambdaQueryWrapper<SysUserTixianLog> sutlLqw=  new LambdaQueryWrapper<>();
            sutlLqw.eq(SysUserTixianLog::getUserId,userVoId);
            sutlLqw.eq(SysUserTixianLog::getTixianStatus,"1");
            List<SysUserTixianLog> sysUserTixianLogList = this.sysUserTixianLogDao.selectList(sutlLqw);
            for(SysUserTixianLog sysUserTixianLog:sysUserTixianLogList){
                sysUserTixianLog.setTixianStatus("3");
                sysUserTixianLog.setRemark("账号冻结，提现撤回！");
                BigDecimal tixianPrice = sysUserTixianLog.getTixianPrice();
                balance1 = balance1.add(tixianPrice);
                this.sysUserTixianLogDao.updateById(sysUserTixianLog);
            }
            sysUser.setBalance(balance1);
            this.updateById(sysUser);

            String key = CacheKeyContants.MILI_USER_TOKEN+userVoId;
            this.redisUtil.del(key);
            return R.success();
        }else{
            return R.error("操作失败");
        }
    }

    /**
     * 商务列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public R<PageData<SysUserVo>> selectShangwuPageData(Long pageNo, Long pageSize) {
        SysUserVo sysUserVo = this.selectUserByToken();
        if(sysUserVo == null){
            return R.error("未登录，无权限");
        }
        Page page = new Page(pageNo,pageSize);
        LambdaQueryWrapper<SysUserRole> surLqw = new LambdaQueryWrapper<>();


        return null;
    }

    /**
     * 强制退出
     * @param sysAccount
     * @return
     */
    @Override
    public R<String> qiangzhiLogOut(SysAccount sysAccount) {
        String xianStr = sysAccount.getXianStr();
        String[] split = xianStr.split(",");
        for(String idStr:split){
            Long id = Long.parseLong(idStr);
            String key = CacheKeyContants.MILI_USER_TOKEN+id;
            this.redisUtil.del(key);
        }
        return null;
    }


    @Override
    public R<String> kefuUploadHeaderUrl(MultipartFile uploadFile) {

        SysUserVo sysUserVo = this.selectUserByToken();
        try {
            Date nowTime = new Date();
            Long userId = sysUserVo.getId();
            String jiazhuangTouxiang = "jzKefuSubmitLiangfangImage/"+DateUtil.formatDate(nowTime, DateUtil.yyyy_mm_dd_hh_mm_ss)+"_"+userId+".PNG";
            InputStream inputStream = uploadFile.getInputStream();
            AliYunOssResult uploadResult = this.aliYunOssServer.upload(inputStream, jiazhuangTouxiang);
            if(uploadResult != null){
                String url = uploadResult.getUrl();
                SysUser sysUser = this.getById(userId);
                sysUser.setHeaderUrl(url);
                this.updateById(sysUser);
                return R.success(uploadResult.getUrl());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public R<List<SysUserXianVo>> selectSysUserXianVoList(Long id) {
        SysUserVo sysUserVo = this.selectUserByToken();
        if(sysUserVo == null){
            return R.error("未登录，无权限！");
        }


        List<SysUserXianVo> returnList = new ArrayList<>();
        SysUser sysUser = this.getById(id);
        if(sysUser == null){
            return R.success(returnList);
        }
        SysUserXianVo returnVo1 = new SysUserXianVo();
        returnVo1.setContent(sysUser.getPhone());
        returnVo1.setTimestamp(DateUtil.formatDate(sysUser.getCreateDate(),DateUtil.YYYY_MM_DD_HH_MM_SS)+"    id ( "+id+" )");
        if(StatusEnum.OK.getCode().equals(sysUser.getStatus())){
            returnVo1.setType("success");
        }else if(StatusEnum.DONGJIE.getCode().equals(sysUser.getStatus())){
            returnVo1.setType("danger");
        }
        returnVo1.setLevelId(sysUser.getLevelId());
        returnVo1.setCreateDate(sysUser.getCreateDate());
        returnVo1.setSize("large");
        returnVo1.setIcon("el-icon-s-custom");
        returnList.add(returnVo1);
        LambdaQueryWrapper<SysAccount> saLqw = new LambdaQueryWrapper<>();
        saLqw.eq(SysAccount::getUserId,id);
        SysAccount sysAccount = this.sysAccountService.getOne(saLqw, Boolean.FALSE);
        if(sysAccount == null || org.apache.commons.lang.StringUtils.isBlank(sysAccount.getXianStr())){
            return R.success(returnList);
        }
        String xianStr = sysAccount.getXianStr();
        xianStr = xianStr.replace(","+id+",",",");
        String[] splitArr = xianStr.split(",");
        LambdaQueryWrapper<SysUser> suLqw = new LambdaQueryWrapper<>();
        suLqw.in(SysUser::getId,splitArr);
        suLqw.orderByDesc(SysUser::getId);
        List<SysUser> sysUserList = this.list(suLqw);
        for(SysUser sysUser1:sysUserList){
            SysUserXianVo xianItemVo = new SysUserXianVo();
            xianItemVo.setIcon("el-icon-top");
            xianItemVo.setSize("normal");
            xianItemVo.setContent(sysUser1.getPhone());

            if(StatusEnum.OK.getCode().equals(sysUser1.getStatus())){
                xianItemVo.setType("success");
            }else if(StatusEnum.DONGJIE.getCode().equals(sysUser1.getStatus())){
                xianItemVo.setType("danger");
            }
            xianItemVo.setCreateDate(sysUser1.getCreateDate());
            xianItemVo.setLevelId(sysUser1.getLevelId());
            returnList.add(xianItemVo);
        }

        for(SysUserXianVo sysUser1:returnList){
            SysUserXianVo xianItemVo = new SysUserXianVo();

            String levelValue = "普通";
            Long levelId = sysUser1.getLevelId();
            if(levelId != null){
                if("1".equals(levelId.toString())){
                    levelValue = "黄金";
                }else if("2".equals(levelId.toString())){
                    levelValue = "白金";
                }else if("3".equals(levelId.toString())){
                    levelValue = "钻石";
                }else if("4".equals(levelId.toString())){
                    levelValue = "初级合伙人";
                }else if("5".equals(levelId.toString())){
                    levelValue = "中级合伙人";
                }else if("6".equals(levelId.toString())){
                    levelValue = "高级合伙人";
                }
            }

            sysUser1.setTimestamp(DateUtil.formatDate(sysUser1.getCreateDate(),DateUtil.YYYY_MM_DD_HH_MM_SS)+"      ( "+levelValue+" )");
        }
        Collections.reverse(returnList);
        return R.success(returnList);
    }

    // 奖池详情
    @Override
    public R<SysRewardInfoVo> selectRewardInfoVo() {
        SysUserVo sysUserVo = this.selectUserByToken();
        SysRewardInfoVo returnVo = new SysRewardInfoVo();
        if(sysUserVo == null){
            return R.success(returnVo);
        }
        Long levelId = sysUserVo.getLevelId();

        BigDecimal prizePoolBalance = this.sysDictDataService.selectPrizePoolBalance();
        returnVo.setRewardPool(prizePoolBalance);
        returnVo.setCanGetReward(prizePoolBalance);

        return R.success(returnVo);
    }

    // 规则详情
    @Override
    public R<SysRewardInfoVo> selectRewardRuleVo() {
        SysUserVo sysUserVo = this.selectUserByToken();
        SysRewardInfoVo returnVo = new SysRewardInfoVo();
        if(sysUserVo == null){
            return R.success(returnVo);
        }
        Long userVoId = sysUserVo.getId();
        Long levelId = sysUserVo.getLevelId();
        if(levelId == null){
            levelId = 0L;
        }
        String levelIcon = "";
        String levelValue = "普通";
        // 成长值
        Integer chengzhangzhi = 0;
        // 成长值 value
        String chengzhangzhiValue = "当前成长值 ： "+chengzhangzhi;
        // 距离下等级成长值
        Integer nextLevelChengzhangzhi = 0;
        // 距离下等级成长值 value
        String nextLevelChengzhangzhiValue = "";
        // 距离下等级成长值 value2
        String nextLevelChengzhangzhiValue2 = "";

        DailiPrizePoolLevel currentPrizePoolLevel = null;
        Integer currentLevelIndex = null;
        if(currentPrizePoolLevel != null){
            levelValue = currentPrizePoolLevel.getTitle();
            levelIcon = currentPrizePoolLevel.getIcon();
        }else{
            currentLevelIndex = -1;
        }





        return R.success(returnVo);
    }

    /**
     * 注销账号
     * @return
     */
    @Override
    public R<String> zhuxiaoZhanghao() {
        SysUserVo sysUserVo = this.selectUserByToken();
        if(sysUserVo == null){
            return R.error("未登录！");
        }
        Long id = sysUserVo.getId();
        SysUser sysUser = this.getById(id);
        sysUser.setStatus(StatusEnum.ZHUXIAO.getCode());
        sysUser.setUpdateDate(new Date());
        boolean isSuccess = this.updateById(sysUser);
        if(isSuccess){
            String tokenKey = CacheKeyContants.MILI_USER_TOKEN+id;
            this.redisUtil.del(tokenKey);
            return R.success();
        }else{
            return R.error("注销失败");
        }
    }



}
